-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathScheduledPublisher.ts
More file actions
39 lines (33 loc) · 1.07 KB
/
ScheduledPublisher.ts
File metadata and controls
39 lines (33 loc) · 1.07 KB
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
import type { Scheduler } from "../schedulers/Scheduler";
import type { Publisher } from "./Publisher";
export class ScheduledPublisher<T> implements Publisher<T> {
private scheduler: Scheduler;
private subscribers: ((value: T) => void)[];
private handlePublishError: (error: unknown, value: T) => void;
constructor(
scheduler: Scheduler,
options?: { handlePublishError?: (error: unknown, value: T) => void },
) {
this.scheduler = scheduler;
this.subscribers = [];
this.handlePublishError = options?.handlePublishError ?? (() => {});
}
publish(value: T): void {
const subscribers = this.subscribers.slice();
this.scheduler.schedule(async () => {
for (const subscriber of subscribers) {
try {
subscriber(value);
} catch (error) {
this.handlePublishError(error, value);
}
}
});
}
subscribe(subscriber: (value: T) => void): () => void {
this.subscribers.push(subscriber);
return () => {
this.subscribers = this.subscribers.filter((s) => s !== subscriber);
};
}
}