1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.Combinator = void 0;
|
7 |
|
8 | var _util = require("@polkadot/util");
|
9 |
|
10 |
|
11 |
|
12 | class Combinator {
|
13 | #allHasFired = false;
|
14 | #callback;
|
15 | #fired = [];
|
16 | #fns = [];
|
17 | #isActive = true;
|
18 | #results = [];
|
19 | #subscriptions = [];
|
20 |
|
21 | constructor(fns, callback) {
|
22 | this.#callback = callback; // eslint-disable-next-line @typescript-eslint/require-await
|
23 |
|
24 | this.#subscriptions = fns.map(async (input, index) => {
|
25 | const [fn, ...args] = Array.isArray(input) ? input : [input];
|
26 | this.#fired.push(false);
|
27 | this.#fns.push(fn); // Not quite 100% how to have a variable number at the front here
|
28 |
|
29 |
|
30 | return fn(...args, this._createCallback(index));
|
31 | });
|
32 | }
|
33 |
|
34 | _allHasFired() {
|
35 | this.#allHasFired || (this.#allHasFired = this.#fired.filter(hasFired => !hasFired).length === 0);
|
36 | return this.#allHasFired;
|
37 | }
|
38 |
|
39 | _createCallback(index) {
|
40 | return value => {
|
41 | this.#fired[index] = true;
|
42 | this.#results[index] = value;
|
43 |
|
44 | this._triggerUpdate();
|
45 | };
|
46 | }
|
47 |
|
48 | _triggerUpdate() {
|
49 | if (!this.#isActive || !(0, _util.isFunction)(this.#callback) || !this._allHasFired()) {
|
50 | return;
|
51 | }
|
52 |
|
53 | try {
|
54 |
|
55 | this.#callback(this.#results);
|
56 | } catch (error) {
|
57 | }
|
58 | }
|
59 |
|
60 | unsubscribe() {
|
61 | if (!this.#isActive) {
|
62 | return;
|
63 | }
|
64 |
|
65 | this.#isActive = false; // eslint-disable-next-line @typescript-eslint/no-misused-promises
|
66 |
|
67 | this.#subscriptions.forEach(async subscription => {
|
68 | try {
|
69 | const unsubscribe = await subscription;
|
70 |
|
71 | if ((0, _util.isFunction)(unsubscribe)) {
|
72 | unsubscribe();
|
73 | }
|
74 | } catch (error) {
|
75 | }
|
76 | });
|
77 | }
|
78 |
|
79 | }
|
80 |
|
81 | exports.Combinator = Combinator; |
\ | No newline at end of file |