Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
}
})();