Debian Codegraph @

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

raw
1 import { Observable } from '../Observable';
2 import { ObservedValueOf, ObservableInputTuple, ObservableInput } from '../types';
3 import { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';
4 import { innerFrom } from './innerFrom';
5 import { popResultSelector } from '../util/args';
6 import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
7 import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
8 import { createObject } from '../util/createObject';
9 import { AnyCatcher } from '../AnyCatcher';
10
11 // forkJoin(any)
12 // We put this first because we need to catch cases where the user has supplied
13 // _exactly `any`_ as the argument. Since `any` literally matches _anything_,
14 // we don't want it to randomly hit one of the other type signatures below,
15 // as we have no idea at build-time what type we should be returning when given an any.
16
17 /**
18 * You have passed `any` here, we can't figure out if it is
19 * an array or an object, so you're getting `unknown`. Use better types.
20 * @param arg Something typed as `any`
21 */
22 export function forkJoin<T extends AnyCatcher>(arg: T): Observable<unknown>;
23
24 // forkJoin(null | undefined)
25 export function forkJoin(scheduler: null | undefined): Observable<never>;
26
27 // forkJoin([a, b, c])
28 export function forkJoin(sources: readonly []): Observable<never>;
29 export function forkJoin<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;
30 export function forkJoin<A extends readonly unknown[], R>(
31 sources: readonly [...ObservableInputTuple<A>],
32 resultSelector: (...values: A) => R
33 ): Observable<R>;
34
35 // forkJoin(a, b, c)
36 /** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
37 export function forkJoin<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;
38 /** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
39 export function forkJoin<A extends readonly unknown[], R>(
40 ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]
41 ): Observable<R>;
42
43 // forkJoin({a, b, c})
44 export function forkJoin(sourcesObject: { [K in any]: never }): Observable<never>;
45 export function forkJoin<T extends Record<string, ObservableInput<any>>>(
46 sourcesObject: T
47 ): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;
48
49 /**
50 * Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns
51 * an {@link Observable} that emits either an array of values in the exact same order as the passed array,
52 * or a dictionary of values in the same shape as the passed dictionary.
53 *
54 * <span class="informal">Wait for Observables to complete and then combine last values they emitted;
55 * complete immediately if an empty array is passed.</span>
56 *
57 * ![](forkJoin.png)
58 *
59 * `forkJoin` is an operator that takes any number of input observables which can be passed either as an array
60 * or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed),
61 * then the resulting stream will complete immediately.
62 *
63 * `forkJoin` will wait for all passed observables to emit and complete and then it will emit an array or an object with last
64 * values from corresponding observables.
65 *
66 * If you pass an array of `n` observables to the operator, then the resulting
67 * array will have `n` values, where the first value is the last one emitted by the first observable,
68 * second value is the last one emitted by the second observable and so on.
69 *
70 * If you pass a dictionary of observables to the operator, then the resulting
71 * objects will have the same keys as the dictionary passed, with their last values they have emitted
72 * located at the corresponding key.
73 *
74 * That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined
75 * values not only at the end of the lifecycle of passed observables, but also throughout it, try out {@link combineLatest}
76 * or {@link zip} instead.
77 *
78 * In order for the resulting array to have the same length as the number of input observables, whenever any of
79 * the given observables completes without emitting any value, `forkJoin` will complete at that moment as well
80 * and it will not emit anything either, even if it already has some last values from other observables.
81 * Conversely, if there is an observable that never completes, `forkJoin` will never complete either,
82 * unless at any point some other observable completes without emitting a value, which brings us back to
83 * the previous case. Overall, in order for `forkJoin` to emit a value, all given observables
84 * have to emit something at least once and complete.
85 *
86 * If any given observable errors at some point, `forkJoin` will error as well and immediately unsubscribe
87 * from the other observables.
88 *
89 * Optionally `forkJoin` accepts a `resultSelector` function, that will be called with values which normally
90 * would land in the emitted array. Whatever is returned by the `resultSelector`, will appear in the output
91 * observable instead. This means that the default `resultSelector` can be thought of as a function that takes
92 * all its arguments and puts them into an array. Note that the `resultSelector` will be called only
93 * when `forkJoin` is supposed to emit a result.
94 *
95 * ## Examples
96 *
97 * Use `forkJoin` with a dictionary of observable inputs
98 *
99 * ```ts
100 * import { forkJoin, of, timer } from 'rxjs';
101 *
102 * const observable = forkJoin({
103 * foo: of(1, 2, 3, 4),
104 * bar: Promise.resolve(8),
105 * baz: timer(4000)
106 * });
107 * observable.subscribe({
108 * next: value => console.log(value),
109 * complete: () => console.log('This is how it ends!'),
110 * });
111 *
112 * // Logs:
113 * // { foo: 4, bar: 8, baz: 0 } after 4 seconds
114 * // 'This is how it ends!' immediately after
115 * ```
116 *
117 * Use `forkJoin` with an array of observable inputs
118 *
119 * ```ts
120 * import { forkJoin, of, timer } from 'rxjs';
121 *
122 * const observable = forkJoin([
123 * of(1, 2, 3, 4),
124 * Promise.resolve(8),
125 * timer(4000)
126 * ]);
127 * observable.subscribe({
128 * next: value => console.log(value),
129 * complete: () => console.log('This is how it ends!'),
130 * });
131 *
132 * // Logs:
133 * // [4, 8, 0] after 4 seconds
134 * // 'This is how it ends!' immediately after
135 * ```
136 *
137 * @see {@link combineLatest}
138 * @see {@link zip}
139 *
140 * @param args Any number of `ObservableInput`s provided either as an array, as an object
141 * or as arguments passed directly to the operator.
142 * @return Observable emitting either an array of last values emitted by passed Observables
143 * or value from project function.
144 */
145 export function forkJoin(...args: any[]): Observable<any> {
146 const resultSelector = popResultSelector(args);
147 const { args: sources, keys } = argsArgArrayOrObject(args);
148 const result = new Observable((subscriber) => {
149 const { length } = sources;
150 if (!length) {
151 subscriber.complete();
152 return;
153 }
154 const values = new Array(length);
155 let remainingCompletions = length;
156 let remainingEmissions = length;
157 for (let sourceIndex = 0; sourceIndex < length; sourceIndex++) {
158 let hasValue = false;
159 innerFrom(sources[sourceIndex]).subscribe(
160 createOperatorSubscriber(
161 subscriber,
162 (value) => {
163 if (!hasValue) {
164 hasValue = true;
165 remainingEmissions--;
166 }
167 values[sourceIndex] = value;
168 },
169 () => remainingCompletions--,
170 undefined,
171 () => {
172 if (!remainingCompletions || !hasValue) {
173 if (!remainingEmissions) {
174 subscriber.next(keys ? createObject(keys, values) : values);
175 }
176 subscriber.complete();
177 }
178 }
179 )
180 );
181 }
182 });
183 return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;
184 }