Debian Codegraph @

node/rxjs/src/internal/operators/switchScan.ts

raw
1 import { ObservableInput, ObservedValueOf, OperatorFunction } from '../types';
2 import { switchMap } from './switchMap';
3 import { operate } from '../util/lift';
4
5 // TODO: Generate a marble diagram for these docs.
6
7 /**
8 * Applies an accumulator function over the source Observable where the
9 * accumulator function itself returns an Observable, emitting values
10 * only from the most recently returned Observable.
11 *
12 * <span class="informal">It's like {@link mergeScan}, but only the most recent
13 * Observable returned by the accumulator is merged into the outer Observable.</span>
14 *
15 * @see {@link scan}
16 * @see {@link mergeScan}
17 * @see {@link switchMap}
18 *
19 * @param accumulator
20 * The accumulator function called on each source value.
21 * @param seed The initial accumulation value.
22 * @return A function that returns an observable of the accumulated values.
23 */
24 export function switchScan<T, R, O extends ObservableInput<any>>(
25 accumulator: (acc: R, value: T, index: number) => O,
26 seed: R
27 ): OperatorFunction<T, ObservedValueOf<O>> {
28 return operate((source, subscriber) => {
29 // The state we will keep up to date to pass into our
30 // accumulator function at each new value from the source.
31 let state = seed;
32
33 // Use `switchMap` on our `source` to do the work of creating
34 // this operator. Note the backwards order here of `switchMap()(source)`
35 // to avoid needing to use `pipe` unnecessarily
36 switchMap(
37 // On each value from the source, call the accumulator with
38 // our previous state, the value and the index.
39 (value: T, index) => accumulator(state, value, index),
40 // Using the deprecated result selector here as a dirty trick
41 // to update our state with the flattened value.
42 (_, innerValue) => ((state = innerValue), innerValue)
43 )(source).subscribe(subscriber);
44
45 return () => {
46 // Release state on finalization
47 state = null!;
48 };
49 });
50 }