UNPKG

2.05 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.Combinator = void 0;
7
8var _util = require("@polkadot/util");
9
10// Copyright 2017-2022 @polkadot/api authors & contributors
11// SPDX-License-Identifier: Apache-2.0
12class 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 // eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/ban-types
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 // eslint-disable-next-line @typescript-eslint/no-floating-promises
55 this.#callback(this.#results);
56 } catch (error) {// swallow, we don't want the handler to trip us up
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) {// ignore
75 }
76 });
77 }
78
79}
80
81exports.Combinator = Combinator;
\No newline at end of file