Debian Codegraph @

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

raw
1 import { OperatorFunction, ObservableInputTuple } from '../types';
2 import { operate } from '../util/lift';
3 import { createOperatorSubscriber } from './OperatorSubscriber';
4 import { innerFrom } from '../observable/innerFrom';
5 import { identity } from '../util/identity';
6 import { noop } from '../util/noop';
7 import { popResultSelector } from '../util/args';
8
9 export function withLatestFrom<T, O extends unknown[]>(...inputs: [...ObservableInputTuple<O>]): OperatorFunction<T, [T, ...O]>;
10
11 export function withLatestFrom<T, O extends unknown[], R>(
12 ...inputs: [...ObservableInputTuple<O>, (...value: [T, ...O]) => R]
13 ): OperatorFunction<T, R>;
14
15 /**
16 * Combines the source Observable with other Observables to create an Observable
17 * whose values are calculated from the latest values of each, only when the
18 * source emits.
19 *
20 * <span class="informal">Whenever the source Observable emits a value, it
21 * computes a formula using that value plus the latest values from other input
22 * Observables, then emits the output of that formula.</span>
23 *
24 * ![](withLatestFrom.png)
25 *
26 * `withLatestFrom` combines each value from the source Observable (the
27 * instance) with the latest values from the other input Observables only when
28 * the source emits a value, optionally using a `project` function to determine
29 * the value to be emitted on the output Observable. All input Observables must
30 * emit at least one value before the output Observable will emit a value.
31 *
32 * ## Example
33 *
34 * On every click event, emit an array with the latest timer event plus the click event
35 *
36 * ```ts
37 * import { fromEvent, interval, withLatestFrom } from 'rxjs';
38 *
39 * const clicks = fromEvent(document, 'click');
40 * const timer = interval(1000);
41 * const result = clicks.pipe(withLatestFrom(timer));
42 * result.subscribe(x => console.log(x));
43 * ```
44 *
45 * @see {@link combineLatest}
46 *
47 * @param inputs An input Observable to combine with the source Observable. More
48 * than one input Observables may be given as argument. If the last parameter is
49 * a function, it will be used as a projection function for combining values
50 * together. When the function is called, it receives all values in order of the
51 * Observables passed, where the first parameter is a value from the source
52 * Observable. (e.g.
53 * `a.pipe(withLatestFrom(b, c), map(([a1, b1, c1]) => a1 + b1 + c1))`). If this
54 * is not passed, arrays will be emitted on the output Observable.
55 * @return A function that returns an Observable of projected values from the
56 * most recent values from each input Observable, or an array of the most
57 * recent values from each input Observable.
58 */
59 export function withLatestFrom<T, R>(...inputs: any[]): OperatorFunction<T, R | any[]> {
60 const project = popResultSelector(inputs) as ((...args: any[]) => R) | undefined;
61
62 return operate((source, subscriber) => {
63 const len = inputs.length;
64 const otherValues = new Array(len);
65 // An array of whether or not the other sources have emitted. Matched with them by index.
66 // TODO: At somepoint, we should investigate the performance implications here, and look
67 // into using a `Set()` and checking the `size` to see if we're ready.
68 let hasValue = inputs.map(() => false);
69 // Flipped true when we have at least one value from all other sources and
70 // we are ready to start emitting values.
71 let ready = false;
72
73 // Other sources. Note that here we are not checking `subscriber.closed`,
74 // this causes all inputs to be subscribed to, even if nothing can be emitted
75 // from them. This is an important distinction because subscription constitutes
76 // a side-effect.
77 for (let i = 0; i < len; i++) {
78 innerFrom(inputs[i]).subscribe(
79 createOperatorSubscriber(
80 subscriber,
81 (value) => {
82 otherValues[i] = value;
83 if (!ready && !hasValue[i]) {
84 // If we're not ready yet, flag to show this observable has emitted.
85 hasValue[i] = true;
86 // Intentionally terse code.
87 // If all of our other observables have emitted, set `ready` to `true`,
88 // so we know we can start emitting values, then clean up the `hasValue` array,
89 // because we don't need it anymore.
90 (ready = hasValue.every(identity)) && (hasValue = null!);
91 }
92 },
93 // Completing one of the other sources has
94 // no bearing on the completion of our result.
95 noop
96 )
97 );
98 }
99
100 // Source subscription
101 source.subscribe(
102 createOperatorSubscriber(subscriber, (value) => {
103 if (ready) {
104 // We have at least one value from the other sources. Go ahead and emit.
105 const values = [value, ...otherValues];
106 subscriber.next(project ? project(...values) : values);
107 }
108 })
109 );
110 });
111 }