Debian Codegraph @

node/rxjs/src/internal/observable/combineLatest.ts

raw
1 import { Observable } from '../Observable';
2 import { ObservableInput, SchedulerLike, ObservedValueOf, ObservableInputTuple } from '../types';
3 import { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';
4 import { Subscriber } from '../Subscriber';
5 import { from } from './from';
6 import { identity } from '../util/identity';
7 import { Subscription } from '../Subscription';
8 import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
9 import { popResultSelector, popScheduler } from '../util/args';
10 import { createObject } from '../util/createObject';
11 import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
12 import { AnyCatcher } from '../AnyCatcher';
13 import { executeSchedule } from '../util/executeSchedule';
14
15 // combineLatest(any)
16 // We put this first because we need to catch cases where the user has supplied
17 // _exactly `any`_ as the argument. Since `any` literally matches _anything_,
18 // we don't want it to randomly hit one of the other type signatures below,
19 // as we have no idea at build-time what type we should be returning when given an any.
20
21 /**
22 * You have passed `any` here, we can't figure out if it is
23 * an array or an object, so you're getting `unknown`. Use better types.
24 * @param arg Something typed as `any`
25 */
26 export function combineLatest<T extends AnyCatcher>(arg: T): Observable<unknown>;
27
28 // combineLatest([a, b, c])
29 export function combineLatest(sources: []): Observable<never>;
30 export function combineLatest<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;
31 /** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
32 export function combineLatest<A extends readonly unknown[], R>(
33 sources: readonly [...ObservableInputTuple<A>],
34 resultSelector: (...values: A) => R,
35 scheduler: SchedulerLike
36 ): Observable<R>;
37 export function combineLatest<A extends readonly unknown[], R>(
38 sources: readonly [...ObservableInputTuple<A>],
39 resultSelector: (...values: A) => R
40 ): Observable<R>;
41 /** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
42 export function combineLatest<A extends readonly unknown[]>(
43 sources: readonly [...ObservableInputTuple<A>],
44 scheduler: SchedulerLike
45 ): Observable<A>;
46
47 // combineLatest(a, b, c)
48 /** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
49 export function combineLatest<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;
50 /** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
51 export function combineLatest<A extends readonly unknown[], R>(
52 ...sourcesAndResultSelectorAndScheduler: [...ObservableInputTuple<A>, (...values: A) => R, SchedulerLike]
53 ): Observable<R>;
54 /** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
55 export function combineLatest<A extends readonly unknown[], R>(
56 ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]
57 ): Observable<R>;
58 /** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
59 export function combineLatest<A extends readonly unknown[]>(
60 ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]
61 ): Observable<A>;
62
63 // combineLatest({a, b, c})
64 export function combineLatest(sourcesObject: { [K in any]: never }): Observable<never>;
65 export function combineLatest<T extends Record<string, ObservableInput<any>>>(
66 sourcesObject: T
67 ): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;
68
69 /**
70 * Combines multiple Observables to create an Observable whose values are
71 * calculated from the latest values of each of its input Observables.
72 *
73 * <span class="informal">Whenever any input Observable emits a value, it
74 * computes a formula using the latest values from all the inputs, then emits
75 * the output of that formula.</span>
76 *
77 * ![](combineLatest.png)
78 *
79 * `combineLatest` combines the values from all the Observables passed in the
80 * observables array. This is done by subscribing to each Observable in order and,
81 * whenever any Observable emits, collecting an array of the most recent
82 * values from each Observable. So if you pass `n` Observables to this operator,
83 * the returned Observable will always emit an array of `n` values, in an order
84 * corresponding to the order of the passed Observables (the value from the first Observable
85 * will be at index 0 of the array and so on).
86 *
87 * Static version of `combineLatest` accepts an array of Observables. Note that an array of
88 * Observables is a good choice, if you don't know beforehand how many Observables
89 * you will combine. Passing an empty array will result in an Observable that
90 * completes immediately.
91 *
92 * To ensure the output array always has the same length, `combineLatest` will
93 * actually wait for all input Observables to emit at least once,
94 * before it starts emitting results. This means if some Observable emits
95 * values before other Observables started emitting, all these values but the last
96 * will be lost. On the other hand, if some Observable does not emit a value but
97 * completes, resulting Observable will complete at the same moment without
98 * emitting anything, since it will now be impossible to include a value from the
99 * completed Observable in the resulting array. Also, if some input Observable does
100 * not emit any value and never completes, `combineLatest` will also never emit
101 * and never complete, since, again, it will wait for all streams to emit some
102 * value.
103 *
104 * If at least one Observable was passed to `combineLatest` and all passed Observables
105 * emitted something, the resulting Observable will complete when all combined
106 * streams complete. So even if some Observable completes, the result of
107 * `combineLatest` will still emit values when other Observables do. In case
108 * of a completed Observable, its value from now on will always be the last
109 * emitted value. On the other hand, if any Observable errors, `combineLatest`
110 * will error immediately as well, and all other Observables will be unsubscribed.
111 *
112 * ## Examples
113 *
114 * Combine two timer Observables
115 *
116 * ```ts
117 * import { timer, combineLatest } from 'rxjs';
118 *
119 * const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
120 * const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
121 * const combinedTimers = combineLatest([firstTimer, secondTimer]);
122 * combinedTimers.subscribe(value => console.log(value));
123 * // Logs
124 * // [0, 0] after 0.5s
125 * // [1, 0] after 1s
126 * // [1, 1] after 1.5s
127 * // [2, 1] after 2s
128 * ```
129 *
130 * Combine a dictionary of Observables
131 *
132 * ```ts
133 * import { of, delay, startWith, combineLatest } from 'rxjs';
134 *
135 * const observables = {
136 * a: of(1).pipe(delay(1000), startWith(0)),
137 * b: of(5).pipe(delay(5000), startWith(0)),
138 * c: of(10).pipe(delay(10000), startWith(0))
139 * };
140 * const combined = combineLatest(observables);
141 * combined.subscribe(value => console.log(value));
142 * // Logs
143 * // { a: 0, b: 0, c: 0 } immediately
144 * // { a: 1, b: 0, c: 0 } after 1s
145 * // { a: 1, b: 5, c: 0 } after 5s
146 * // { a: 1, b: 5, c: 10 } after 10s
147 * ```
148 *
149 * Combine an array of Observables
150 *
151 * ```ts
152 * import { of, delay, startWith, combineLatest } from 'rxjs';
153 *
154 * const observables = [1, 5, 10].map(
155 * n => of(n).pipe(
156 * delay(n * 1000), // emit 0 and then emit n after n seconds
157 * startWith(0)
158 * )
159 * );
160 * const combined = combineLatest(observables);
161 * combined.subscribe(value => console.log(value));
162 * // Logs
163 * // [0, 0, 0] immediately
164 * // [1, 0, 0] after 1s
165 * // [1, 5, 0] after 5s
166 * // [1, 5, 10] after 10s
167 * ```
168 *
169 * Use map operator to dynamically calculate the Body-Mass Index
170 *
171 * ```ts
172 * import { of, combineLatest, map } from 'rxjs';
173 *
174 * const weight = of(70, 72, 76, 79, 75);
175 * const height = of(1.76, 1.77, 1.78);
176 * const bmi = combineLatest([weight, height]).pipe(
177 * map(([w, h]) => w / (h * h)),
178 * );
179 * bmi.subscribe(x => console.log('BMI is ' + x));
180 *
181 * // With output to console:
182 * // BMI is 24.212293388429753
183 * // BMI is 23.93948099205209
184 * // BMI is 23.671253629592222
185 * ```
186 *
187 * @see {@link combineLatestAll}
188 * @see {@link merge}
189 * @see {@link withLatestFrom}
190 *
191 * @param args Any number of `ObservableInput`s provided either as an array or as an object
192 * to combine with each other. If the last parameter is the function, it will be used to project the
193 * values from the combined latest values into a new value on the output Observable.
194 * @return An Observable of projected values from the most recent values from each `ObservableInput`,
195 * or an array of the most recent values from each `ObservableInput`.
196 */
197 export function combineLatest<O extends ObservableInput<any>, R>(...args: any[]): Observable<R> | Observable<ObservedValueOf<O>[]> {
198 const scheduler = popScheduler(args);
199 const resultSelector = popResultSelector(args);
200
201 const { args: observables, keys } = argsArgArrayOrObject(args);
202
203 if (observables.length === 0) {
204 // If no observables are passed, or someone has passed an empty array
205 // of observables, or even an empty object POJO, we need to just
206 // complete (EMPTY), but we have to honor the scheduler provided if any.
207 return from([], scheduler as any);
208 }
209
210 const result = new Observable<ObservedValueOf<O>[]>(
211 combineLatestInit(
212 observables as ObservableInput<ObservedValueOf<O>>[],
213 scheduler,
214 keys
215 ? // A handler for scrubbing the array of args into a dictionary.
216 (values) => createObject(keys, values)
217 : // A passthrough to just return the array
218 identity
219 )
220 );
221
222 return resultSelector ? (result.pipe(mapOneOrManyArgs(resultSelector)) as Observable<R>) : result;
223 }
224
225 export function combineLatestInit(
226 observables: ObservableInput<any>[],
227 scheduler?: SchedulerLike,
228 valueTransform: (values: any[]) => any = identity
229 ) {
230 return (subscriber: Subscriber<any>) => {
231 // The outer subscription. We're capturing this in a function
232 // because we may have to schedule it.
233 maybeSchedule(
234 scheduler,
235 () => {
236 const { length } = observables;
237 // A store for the values each observable has emitted so far. We match observable to value on index.
238 const values = new Array(length);
239 // The number of currently active subscriptions, as they complete, we decrement this number to see if
240 // we are all done combining values, so we can complete the result.
241 let active = length;
242 // The number of inner sources that still haven't emitted the first value
243 // We need to track this because all sources need to emit one value in order
244 // to start emitting values.
245 let remainingFirstValues = length;
246 // The loop to kick off subscription. We're keying everything on index `i` to relate the observables passed
247 // in to the slot in the output array or the key in the array of keys in the output dictionary.
248 for (let i = 0; i < length; i++) {
249 maybeSchedule(
250 scheduler,
251 () => {
252 const source = from(observables[i], scheduler as any);
253 let hasFirstValue = false;
254 source.subscribe(
255 createOperatorSubscriber(
256 subscriber,
257 (value) => {
258 // When we get a value, record it in our set of values.
259 values[i] = value;
260 if (!hasFirstValue) {
261 // If this is our first value, record that.
262 hasFirstValue = true;
263 remainingFirstValues--;
264 }
265 if (!remainingFirstValues) {
266 // We're not waiting for any more
267 // first values, so we can emit!
268 subscriber.next(valueTransform(values.slice()));
269 }
270 },
271 () => {
272 if (!--active) {
273 // We only complete the result if we have no more active
274 // inner observables.
275 subscriber.complete();
276 }
277 }
278 )
279 );
280 },
281 subscriber
282 );
283 }
284 },
285 subscriber
286 );
287 };
288 }
289
290 /**
291 * A small utility to handle the couple of locations where we want to schedule if a scheduler was provided,
292 * but we don't if there was no scheduler.
293 */
294 function maybeSchedule(scheduler: SchedulerLike | undefined, execute: () => void, subscription: Subscription) {
295 if (scheduler) {
296 executeSchedule(subscription, scheduler, execute);
297 } else {
298 execute();
299 }
300 }