1 |
|
2 |
|
3 | import { Observer } from 'zen-observable-ts';
|
4 | import { RECONNECT_DELAY, RECONNECT_INTERVAL } from '../Providers/constants';
|
5 |
|
6 | export enum ReconnectEvent {
|
7 | START_RECONNECT = 'START_RECONNECT',
|
8 | HALT_RECONNECT = 'HALT_RECONNECT',
|
9 | }
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export class ReconnectionMonitor {
|
18 | private reconnectObservers: Observer<void>[] = [];
|
19 | private reconnectIntervalId?: ReturnType<typeof setInterval>;
|
20 | private reconnectSetTimeoutId?: ReturnType<typeof setTimeout>;
|
21 |
|
22 | |
23 |
|
24 |
|
25 | addObserver(reconnectObserver: Observer<void>) {
|
26 | this.reconnectObservers.push(reconnectObserver);
|
27 | }
|
28 |
|
29 | |
30 |
|
31 |
|
32 | record(event: ReconnectEvent) {
|
33 | if (event === ReconnectEvent.START_RECONNECT) {
|
34 |
|
35 | if (
|
36 | this.reconnectSetTimeoutId === undefined &&
|
37 | this.reconnectIntervalId === undefined
|
38 | ) {
|
39 | this.reconnectSetTimeoutId = setTimeout(() => {
|
40 |
|
41 | this._triggerReconnect();
|
42 |
|
43 | this.reconnectIntervalId = setInterval(() => {
|
44 | this._triggerReconnect();
|
45 | }, RECONNECT_INTERVAL);
|
46 | }, RECONNECT_DELAY);
|
47 | }
|
48 | }
|
49 |
|
50 | if (event === ReconnectEvent.HALT_RECONNECT) {
|
51 | if (this.reconnectIntervalId) {
|
52 | clearInterval(this.reconnectIntervalId);
|
53 | this.reconnectIntervalId = undefined;
|
54 | }
|
55 | if (this.reconnectSetTimeoutId) {
|
56 | clearTimeout(this.reconnectSetTimeoutId);
|
57 | this.reconnectSetTimeoutId = undefined;
|
58 | }
|
59 | }
|
60 | }
|
61 |
|
62 | |
63 |
|
64 |
|
65 | close() {
|
66 | this.reconnectObservers.forEach(reconnectObserver => {
|
67 | reconnectObserver.complete?.();
|
68 | });
|
69 | }
|
70 |
|
71 | private _triggerReconnect() {
|
72 | this.reconnectObservers.forEach(reconnectObserver => {
|
73 | reconnectObserver.next?.();
|
74 | });
|
75 | }
|
76 | }
|