1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.Combinator = void 0;
|
4 | const util_1 = require("@polkadot/util");
|
5 | class Combinator {
|
6 | __internal__allHasFired = false;
|
7 | __internal__callback;
|
8 | __internal__fired = [];
|
9 | __internal__fns = [];
|
10 | __internal__isActive = true;
|
11 | __internal__results = [];
|
12 | __internal__subscriptions = [];
|
13 | constructor(fns, callback) {
|
14 | this.__internal__callback = callback;
|
15 |
|
16 | this.__internal__subscriptions = fns.map(async (input, index) => {
|
17 | const [fn, ...args] = Array.isArray(input)
|
18 | ? input
|
19 | : [input];
|
20 | this.__internal__fired.push(false);
|
21 | this.__internal__fns.push(fn);
|
22 |
|
23 |
|
24 | return fn(...args, this._createCallback(index));
|
25 | });
|
26 | }
|
27 | _allHasFired() {
|
28 | this.__internal__allHasFired ||= this.__internal__fired.filter((hasFired) => !hasFired).length === 0;
|
29 | return this.__internal__allHasFired;
|
30 | }
|
31 | _createCallback(index) {
|
32 | return (value) => {
|
33 | this.__internal__fired[index] = true;
|
34 | this.__internal__results[index] = value;
|
35 | this._triggerUpdate();
|
36 | };
|
37 | }
|
38 | _triggerUpdate() {
|
39 | if (!this.__internal__isActive || !(0, util_1.isFunction)(this.__internal__callback) || !this._allHasFired()) {
|
40 | return;
|
41 | }
|
42 | try {
|
43 | Promise
|
44 | .resolve(this.__internal__callback(this.__internal__results))
|
45 | .catch(util_1.noop);
|
46 | }
|
47 | catch {
|
48 |
|
49 | }
|
50 | }
|
51 | unsubscribe() {
|
52 | if (!this.__internal__isActive) {
|
53 | return;
|
54 | }
|
55 | this.__internal__isActive = false;
|
56 | Promise
|
57 | .all(this.__internal__subscriptions.map(async (subscription) => {
|
58 | try {
|
59 | const unsubscribe = await subscription;
|
60 | if ((0, util_1.isFunction)(unsubscribe)) {
|
61 | unsubscribe();
|
62 | }
|
63 | }
|
64 | catch {
|
65 |
|
66 | }
|
67 | })).catch(() => {
|
68 |
|
69 | });
|
70 | }
|
71 | }
|
72 | exports.Combinator = Combinator;
|