This repository has been archived by the owner on Oct 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
observer.ts
107 lines (94 loc) · 2.43 KB
/
observer.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import throttle from 'lodash/throttle';
import { Logger } from './logger';
export type OberverOptions = {
throttleTime?: number;
logger?: Logger;
};
export class Observer {
private logger: Logger;
private callbacks: Function[];
private throttle: number;
constructor(options: OberverOptions = {}) {
const { logger, throttleTime } = options;
this.logger = logger ?? new Logger('@superviz/sdk/observer-helper');
this.throttle = throttleTime;
this.callbacks = [];
if (this.throttle) {
this.publish = throttle(this.publish, this.throttle);
}
}
/**
* @function subscribe
* @description Subscribe to observer
* @param callback
* @returns {void}
*/
public subscribe = (callback: Function): void => {
this.callbacks.push(callback);
};
/**
* @function unsubscribe
* @description Unsubscribe from observer
* @param callbackToRemove
* @returns {void}
*/
public unsubscribe = (callbackToRemove: Function): void => {
this.callbacks = this.callbacks.filter((callback: Function) => callback !== callbackToRemove);
};
/**
* @function publish
* @description Publish event to all subscribers
* @param event
* @returns {void}
*/
public publish = (...event: any[]): void => {
if (!this.callbacks) return;
this.callbacks.forEach((callback: Function) => {
this.callListener(callback, event).catch((error: Error) => {
this.logger.log(
'superviz-sdk:observer-helper:publish:error',
`
Failed to execute callback on publish value.
Callback: ${callback}
Event: ${JSON.stringify(event)}
Error: ${error}
`,
);
});
});
};
/**
* @function reset
* @description Reset observer
* @returns {void}
*/
public reset = (): void => {
this.callbacks = [];
};
/**
* @function destroy
* @description Destroy observer
* @returns {void}
*/
public destroy = (): void => {
delete this.logger;
delete this.callbacks;
};
/**
* @function callListener
* @description Call listener with params
* @param listener
* @param params
* @returns
*/
private callListener = (listener: Function, params: any[]): Promise<unknown> => {
return new Promise((resolve, reject) => {
try {
const result = listener(...params);
resolve(result);
} catch (error) {
reject(error);
}
});
};
}