Files
api/packages/rpc-core/src/rxjs/drr.ts
T
Jaco Greeff 2f5e2537a3 Align single-shot memoization (#2546)
* Align single-shot memoization

* Small tweaks

* Test for delayed creates

* With actual sub

* Expand delay test

* Bump delay
2020-08-31 14:31:44 +02:00

50 lines
1.3 KiB
TypeScript

// Copyright 2017-2020 @polkadot/rpc-core authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { Observable } from 'rxjs';
import { catchError, distinctUntilChanged, publishReplay, tap, refCount } from 'rxjs/operators';
import { logger } from '@polkadot/util';
import { refCountDelay } from './refCountDelay';
export type DrrResult = <T> (source$: Observable<T>) => Observable<T>;
interface Options {
delay?: number;
skipChange?: boolean;
skipTimeout?: boolean;
}
const l = logger('drr');
const CMP = (a: unknown, b: unknown): boolean =>
JSON.stringify({ t: a }) === JSON.stringify({ t: b });
const ERR = (error: Error): Observable<never> => {
l.error(error);
throw error;
};
const NOOP = (): void => undefined;
/**
* Shorthand for distinctUntilChanged(), publishReplay(1) and refCount().
*
* @ignore
* @internal
*/
export const drr = ({ delay, skipChange = false, skipTimeout = false }: Options = {}): DrrResult => <T> (source$: Observable<T>): Observable<T> =>
source$.pipe(
catchError(ERR),
skipChange
? tap(NOOP)
: distinctUntilChanged<T>(CMP),
publishReplay(1),
skipTimeout
? refCount()
: refCountDelay(delay)
);