-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServerSentEventsObserver.ts
44 lines (39 loc) · 1.67 KB
/
ServerSentEventsObserver.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
// TODO support custom events and decode payload to object
export class ServerSentEvents {
private eventSource: EventSource = null;
private listeners: ((event: MessageEvent) => void)[] = [];
constructor(private url: string) {}
subscribe(subscriber: (event: MessageEvent) => void) {
if (this.eventSource === null || this.eventSource.readyState === EventSource.CLOSED) {
this.eventSource = new EventSource(this.url);
this.eventSource.onopen = () => {
console.log('ServerSentEvents: connected');
};
this.eventSource.onerror = () => {
console.log('ServerSentEvents: error', this.listeners);
this.listeners.forEach((listener) => {
this.eventSource.addEventListener('message', listener);
});
};
}
this.listeners.push(subscriber);
this.eventSource.addEventListener('message', this.handle.bind(this));
}
unsubscribe(subscriber: (event: MessageEvent) => void) {
if (this.eventSource === null) {
return;
}
this.listeners = this.listeners.filter((listener) => listener !== subscriber);
if (this.eventSource.readyState === EventSource.OPEN && this.listeners.length === 0) {
this.close();
}
}
close() {
this.eventSource.close();
this.eventSource.removeEventListener('message', this.handle.bind(this));
}
private handle(event: MessageEvent) {
this.listeners && this.listeners.forEach((listener) => listener(event));
}
}
export const createServerSentEventsObserver = (url: string) => new ServerSentEvents(url);