Skip to content
Snippets Groups Projects
subscription.handler.ts 1.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { QueryActionCreatorResult } from '@reduxjs/toolkit/query';
    
    type SubscriptionType = QueryActionCreatorResult<any>;
    
    interface SubscriptionEntity {
        subscription: SubscriptionType,
        id: number
    }
    
    interface SubscriptionReducerState {
        subscriptions: SubscriptionEntity[]
    }
    
    
    const initialState: SubscriptionReducerState = {
        subscriptions: []
    }
    
    let state = initialState;
    
    
    export const addSubscription = (subscription: SubscriptionType): number => {
        const id = state.subscriptions.length;
    
        const subscriptionEntity: SubscriptionEntity = {
            subscription,
            id
        }
    
        state.subscriptions = [...state.subscriptions, subscriptionEntity];
    
        return id;
    }
    
    
    export const unsubscribeAll = () => {
        state.subscriptions.forEach(({ subscription }) => {
            unsubscribeAction(subscription)
        });
    
        state.subscriptions = initialState.subscriptions;
    }
    
    /**
     * @param id 
     * @returns returns true if the subscription was stopped, false if it was not found
     */
    export const unsubscribe = (id: number): boolean => {
        const subscription = state.subscriptions.find(({ id: subscriptionId }) => subscriptionId === id);
    
        if (subscription) {
            unsubscribeAction(subscription.subscription);
        }
    
        return !!subscription;
    }
    
    /**
     * Actual unsubscribe action
     * 
     * @param subscription 
     */
    const unsubscribeAction = (subscription: SubscriptionType) => {
        subscription.unsubscribe();
    }