UNPKG

1.89 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/api authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { isFunction } from '@polkadot/util';
4export class Combinator {
5 #allHasFired = false;
6 #callback;
7 #fired = [];
8 #fns = [];
9 #isActive = true;
10 #results = [];
11 #subscriptions = [];
12
13 constructor(fns, callback) {
14 this.#callback = callback; // eslint-disable-next-line @typescript-eslint/require-await
15
16 this.#subscriptions = fns.map(async (input, index) => {
17 const [fn, ...args] = Array.isArray(input) ? input : [input];
18 this.#fired.push(false);
19 this.#fns.push(fn); // Not quite 100% how to have a variable number at the front here
20 // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/ban-types
21
22 return fn(...args, this._createCallback(index));
23 });
24 }
25
26 _allHasFired() {
27 this.#allHasFired || (this.#allHasFired = this.#fired.filter(hasFired => !hasFired).length === 0);
28 return this.#allHasFired;
29 }
30
31 _createCallback(index) {
32 return value => {
33 this.#fired[index] = true;
34 this.#results[index] = value;
35
36 this._triggerUpdate();
37 };
38 }
39
40 _triggerUpdate() {
41 if (!this.#isActive || !isFunction(this.#callback) || !this._allHasFired()) {
42 return;
43 }
44
45 try {
46 // eslint-disable-next-line @typescript-eslint/no-floating-promises
47 this.#callback(this.#results);
48 } catch (error) {// swallow, we don't want the handler to trip us up
49 }
50 }
51
52 unsubscribe() {
53 if (!this.#isActive) {
54 return;
55 }
56
57 this.#isActive = false; // eslint-disable-next-line @typescript-eslint/no-misused-promises
58
59 this.#subscriptions.forEach(async subscription => {
60 try {
61 const unsubscribe = await subscription;
62
63 if (isFunction(unsubscribe)) {
64 unsubscribe();
65 }
66 } catch (error) {// ignore
67 }
68 });
69 }
70
71}
\No newline at end of file