This repository was archived by the owner on May 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathindex.ts
53 lines (48 loc) · 1.59 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity.
//
// SPDX-License-Identifier: MIT
import { combineLatest, from, Observable } from 'rxjs';
import { compose, mapPropsStreamWithConfig } from 'recompose';
import { map, switchMap } from 'rxjs/operators';
import { RpcObservable } from '@parity/light.js';
interface Observables {
[key: string]: RpcObservable<any, any>;
}
/**
* HOC which listens to one Observable, and update the React wrapped component
* every time the Observable fires.
*
* @param key - The key to add the value in `this.props`, so that the value
* will be accessible via `this.props[key]`.
* @param rpc$ - The RpcObservable to listen to.
*/
export const withOneObservable = <OwnProps, T>(
key: string,
rpc$: RpcObservable<any, T>
) =>
mapPropsStreamWithConfig({
// Converts a plain ES observable to an RxJS 6 observable
fromESObservable: from,
toESObservable: stream$ => stream$
})(props$ =>
combineLatest(
props$,
(props$ as Observable<OwnProps>).pipe(switchMap(rpc$))
).pipe(map(([props, value]) => ({ ...props, [key]: value })))
);
/**
* HOC which listens to multiple Observables, and injects those emitted values
* into `this.props`.
*
* @param observables - An object where the keys will be injected into
* `this.props`, and the value of each key will be the value emitted by the
* corresponding Observable.
*/
const light = (observables: Observables) =>
compose(
...Object.keys(observables).map(key =>
withOneObservable(key, observables[key])
)
);
export default light;