Skip to content
Snippets Groups Projects
routine.manager.ts 1.69 KiB
Newer Older
  • Learn to ignore specific revisions
  • Matthias Feyll's avatar
    Matthias Feyll committed
    import { QueryActionCreatorResult } from '@reduxjs/toolkit/query';
    
    type Routine = QueryActionCreatorResult<any>;
    
    interface Entity {
        routine: Routine,
        id: number
    }
    
    const initialState = {
        routines: [] as Entity[]
    }
    
    
    /**
     * Routine manager is a singleton that holds all running routines.
     * The redux store holds any persistable information about the routines.
     * The routines objects itself are stored in the RoutineManager.
     */
    export const RoutineManager = (() => {
        let state = initialState;
        const add = (routine: Routine): number => {
            const id = state.routines.length;
    
            const newEntity: Entity = {
                routine: routine,
                id
            }
    
            state.routines = [...state.routines, newEntity];
    
            return id;
        }
    
    
        const unsubscribeAll = () => {
            state.routines.forEach(({ routine: subscription }) => {
                _unsubscribe(subscription)
            });
    
            state.routines = initialState.routines;
        }
    
        /**
         * @param id 
         * @returns returns true if the routine was stopped, false if it was not found
         */
        const unsubscribe = (id: number): boolean => {
            const routine = state.routines.find(({ id: routineId }) => routineId === id);
    
            if (routine) {
                _unsubscribe(routine.routine);
            }
    
            return !!routine;
        }
    
        /**
         * Actual unsubscribe process.
         * This process is extracted to have a single process of unsubscribing.
         * 
         * @param subscription 
         */
        const _unsubscribe = (subscription: Routine) => {
            subscription.unsubscribe();
            // TODO remove from state
        }
    
    
        return {
            add,
            unsubscribe,
            unsubscribeAll
        }
    })();