Simple subscription results combinator (#327)
* Cleanup docs, refer to api/promise in Base * Simple subscription results combinator * Optional callback in constructtion * Typo in example
This commit is contained in:
+13
-18
@@ -46,12 +46,12 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* import Api from '@polkadot/api/rx';
|
||||
* import Api from '@polkadot/api/promise';
|
||||
*
|
||||
* new Api().isReady.subscribe((api) => {
|
||||
* api.rpc.subscribeNewHead().subscribe((header) => {
|
||||
* console.log(`new block #${header.blockNumber.toNumber()}`);
|
||||
* });
|
||||
* const api = new Api().isReady();
|
||||
*
|
||||
* api.rpc.subscribeNewHead((header) => {
|
||||
* console.log(`new block #${header.blockNumber.toNumber()}`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
@@ -99,11 +99,9 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* api.query.balances
|
||||
* .freeBalance(<accountId>)
|
||||
* .subscribe((balance) => {
|
||||
* console.log('new balance', balance);
|
||||
* });
|
||||
* api.query.balances.freeBalance(<accountId>, (balance) => {
|
||||
* console.log('new balance', balance);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get query (): S {
|
||||
@@ -121,11 +119,9 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* api.rpc.chain
|
||||
* .subscribeNewHead()
|
||||
* .subscribe((header) => {
|
||||
* console.log('new header', header);
|
||||
* });
|
||||
* api.rpc.chain.subscribeNewHead((header) => {
|
||||
* console.log('new header', header);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
get rpc (): R {
|
||||
@@ -142,8 +138,7 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
|
||||
* api.tx.balances
|
||||
* .transfer(<recipientId>, <balance>)
|
||||
* .sign(<keyPair>, <accountNonce>, <blockHash (optional)>)
|
||||
* .send()
|
||||
* .subscribe((status) => {
|
||||
* .send((status) => {
|
||||
* console.log('tx status', status);
|
||||
* });
|
||||
* ```
|
||||
@@ -164,7 +159,7 @@ export default abstract class ApiBase<R, S, E> implements ApiBaseInterface<R, S,
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* * api.on('disconnected', () => {
|
||||
* api.on('disconnected', () => {
|
||||
* console.log('API has been connected to the endpoint');
|
||||
* });
|
||||
*
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
export type CombinatorCallback = (value: Array<any>) => any;
|
||||
export type CombinatorFunction = (cb: (value: any) => void) => any;
|
||||
|
||||
export default class Combinator {
|
||||
protected _allHasFired: boolean = false;
|
||||
protected _callback: CombinatorCallback;
|
||||
protected _fired: Array<boolean> = [];
|
||||
protected _results: Array<any> = [];
|
||||
|
||||
constructor (fns: Array<CombinatorFunction>, callback: CombinatorCallback) {
|
||||
this._callback = callback;
|
||||
|
||||
fns.forEach((fn, index) => {
|
||||
this._fired.push(false);
|
||||
|
||||
fn(this.createCallback(index));
|
||||
});
|
||||
}
|
||||
|
||||
protected allHasFired (): boolean {
|
||||
if (!this._allHasFired) {
|
||||
this._allHasFired = this._fired.filter((hasFired) => !hasFired).length === 0;
|
||||
}
|
||||
|
||||
return this._allHasFired;
|
||||
}
|
||||
|
||||
protected createCallback (index: number) {
|
||||
return (value: any): void => {
|
||||
this._fired[index] = true;
|
||||
this._results[index] = value;
|
||||
|
||||
this.triggerUpdate();
|
||||
};
|
||||
}
|
||||
|
||||
protected triggerUpdate (): void {
|
||||
if (!isFunction(this._callback) || !this.allHasFired()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this._callback(this._results);
|
||||
} catch (error) {
|
||||
// swallow, we don't want the handler to trip us up
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Copyright 2017-2018 @polkadot/api authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import Combinator from './Combinator';
|
||||
|
||||
describe('Combinator', () => {
|
||||
it('it triggers on all values', (done) => {
|
||||
let count = 0;
|
||||
const fns: Array<(value: any) => void> = [];
|
||||
const combinator = new Combinator(
|
||||
[
|
||||
(cb) => fns.push(cb)
|
||||
],
|
||||
(value: Array<any>) => {
|
||||
expect(value[0]).toEqual(`test${count}`);
|
||||
|
||||
count++;
|
||||
|
||||
if (count === 3) {
|
||||
done();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
fns[0]('test0');
|
||||
fns[0]('test1');
|
||||
fns[0]('test2');
|
||||
|
||||
expect(combinator).toBeDefined();
|
||||
});
|
||||
|
||||
it('combines values from 2 sources, firing when it has all results', (done) => {
|
||||
const fns: Array<(value: any) => void> = [];
|
||||
const combinator = new Combinator(
|
||||
[
|
||||
(cb) => fns.push(cb),
|
||||
(cb) => fns.push(cb)
|
||||
],
|
||||
(value: Array<any>) => {
|
||||
expect(value).toEqual(['test0', 'test1']);
|
||||
|
||||
done();
|
||||
}
|
||||
);
|
||||
|
||||
fns[0]('test0');
|
||||
fns[1]('test1');
|
||||
|
||||
expect(combinator).toBeDefined();
|
||||
});
|
||||
|
||||
it('combines values from 2 sources, allowing multiple updates', (done) => {
|
||||
let count = 0;
|
||||
const fns: Array<(value: any) => void> = [];
|
||||
const combinator = new Combinator(
|
||||
[
|
||||
(cb) => fns.push(cb),
|
||||
(cb) => fns.push(cb)
|
||||
],
|
||||
(value: Array<any>) => {
|
||||
expect(value).toEqual(
|
||||
count === 0
|
||||
? ['test0', 'test1']
|
||||
: ['test2', 'test1']);
|
||||
|
||||
count++;
|
||||
|
||||
if (count === 2) {
|
||||
done();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
fns[0]('test0');
|
||||
fns[1]('test1');
|
||||
fns[0]('test2');
|
||||
|
||||
expect(combinator).toBeDefined();
|
||||
});
|
||||
});
|
||||
+4
-2
@@ -9,7 +9,7 @@ import Method from '@polkadot/types/Method';
|
||||
import SubmittableExtrinsic from './SubmittableExtrinsic';
|
||||
|
||||
describe('SubmittableExtrinsic', () => {
|
||||
let api;
|
||||
let api: any;
|
||||
|
||||
beforeEach(() => {
|
||||
Method.injectExtrinsics(extrinsics);
|
||||
@@ -28,7 +28,9 @@ describe('SubmittableExtrinsic', () => {
|
||||
const result = await new SubmittableExtrinsic(
|
||||
api,
|
||||
new Extrinsic('0x010200ea51b75b00000000')
|
||||
).send(() => { });
|
||||
).send(() => {
|
||||
// ignore
|
||||
});
|
||||
|
||||
expect(result).toEqual('submitAndWatchExtrinsic');
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { StorageFunction } from '@polkadot/types/StorageKey';
|
||||
import { isFunction } from '@polkadot/util';
|
||||
|
||||
import ApiBase from '../Base';
|
||||
import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator';
|
||||
import SubmittableExtrinsic from './SubmittableExtrinsic';
|
||||
|
||||
/**
|
||||
@@ -165,6 +166,30 @@ export default class ApiPromise extends ApiBase<Rpc, QueryableStorage, Submittab
|
||||
return rpc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Creates a combinator that can be used to combine the latest results from multiple subscriptions
|
||||
* @param fns An array of function to combine, each in the form of `(cb: (value: void)) => void`
|
||||
* @param callback A callback that will return an Array of all the values this combinator has been applied to
|
||||
* @example
|
||||
* <BR>
|
||||
*
|
||||
* ```javascript
|
||||
* const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';
|
||||
*
|
||||
* // combines values from balance & nonce as it updates
|
||||
* api.combineLatest([
|
||||
* (cb) => api.rpc.chain.subscribeNewHead(cb),
|
||||
* (cb) => api.query.balances.freeBalance(address, cb),
|
||||
* (cb) => api.query.system.accountNonce(address, cb)
|
||||
* ], ([head, balance, nonce]) => {
|
||||
* console.log(`#${head.number}: You have ${balance} units, with ${nonce} transactions sent`);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
combineLatest (fns: Array<CombinatorFunction>, callback: CombinatorCallback): Combinator {
|
||||
return new Combinator(fns, callback);
|
||||
}
|
||||
|
||||
protected decorateExtrinsics (extrinsics: Extrinsics): SubmittableExtrinsics {
|
||||
return Object.keys(extrinsics).reduce((result, sectionName) => {
|
||||
const section = extrinsics[sectionName];
|
||||
|
||||
Reference in New Issue
Block a user