-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribable-event.ts
57 lines (49 loc) · 1.25 KB
/
subscribable-event.ts
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
export class SubscribableEvent<Payload> {
subscriptions: ((payload: Payload) => void | "unsubscribe")[] = [];
emit(payload: Payload) {
this.subscriptions = this.subscriptions.filter(
(s) => s(payload) !== "unsubscribe"
);
}
subscribe(
subscription: (payload: Payload) => void | "unsubscribe"
): Subscription {
this.subscriptions.push(subscription);
return {
unsubscribe: () => {
this.subscriptions = this.subscriptions.filter(
(s) => s !== subscription
);
},
};
}
}
export interface Subscription {
unsubscribe: () => void;
}
export class SubscriptionManager {
subscriptions: Subscription[] = [];
unsubscribeAll() {
this.subscriptions.forEach((subscription) => {
subscription.unsubscribe();
});
this.subscriptions = [];
}
unsubscribe(subscription: Subscription) {
this.subscriptions = this.subscriptions.filter((s) => {
if (s === subscription) {
s.unsubscribe();
return false;
}
return true;
});
}
add(subscription: Subscription) {
this.subscriptions.push(subscription);
}
addMultiple(subscriptions: Subscription[]) {
subscriptions.forEach((subscription) => {
this.add(subscription);
});
}
}