Debian Codegraph @

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

raw
1 import { Observable } from '../Observable';
2 import { innerFrom } from '../observable/innerFrom';
3 import { Subscriber } from '../Subscriber';
4 import { ObservableInput, SchedulerLike } from '../types';
5 import { executeSchedule } from '../util/executeSchedule';
6 import { createOperatorSubscriber } from './OperatorSubscriber';
7
8 /**
9 * A process embodying the general "merge" strategy. This is used in
10 * `mergeMap` and `mergeScan` because the logic is otherwise nearly identical.
11 * @param source The original source observable
12 * @param subscriber The consumer subscriber
13 * @param project The projection function to get our inner sources
14 * @param concurrent The number of concurrent inner subscriptions
15 * @param onBeforeNext Additional logic to apply before nexting to our consumer
16 * @param expand If `true` this will perform an "expand" strategy, which differs only
17 * in that it recurses, and the inner subscription must be schedule-able.
18 * @param innerSubScheduler A scheduler to use to schedule inner subscriptions,
19 * this is to support the expand strategy, mostly, and should be deprecated
20 */
21 export function mergeInternals<T, R>(
22 source: Observable<T>,
23 subscriber: Subscriber<R>,
24 project: (value: T, index: number) => ObservableInput<R>,
25 concurrent: number,
26 onBeforeNext?: (innerValue: R) => void,
27 expand?: boolean,
28 innerSubScheduler?: SchedulerLike,
29 additionalFinalizer?: () => void
30 ) {
31 // Buffered values, in the event of going over our concurrency limit
32 const buffer: T[] = [];
33 // The number of active inner subscriptions.
34 let active = 0;
35 // An index to pass to our accumulator function
36 let index = 0;
37 // Whether or not the outer source has completed.
38 let isComplete = false;
39
40 /**
41 * Checks to see if we can complete our result or not.
42 */
43 const checkComplete = () => {
44 // If the outer has completed, and nothing is left in the buffer,
45 // and we don't have any active inner subscriptions, then we can
46 // Emit the state and complete.
47 if (isComplete && !buffer.length && !active) {
48 subscriber.complete();
49 }
50 };
51
52 // If we're under our concurrency limit, just start the inner subscription, otherwise buffer and wait.
53 const outerNext = (value: T) => (active < concurrent ? doInnerSub(value) : buffer.push(value));
54
55 const doInnerSub = (value: T) => {
56 // If we're expanding, we need to emit the outer values and the inner values
57 // as the inners will "become outers" in a way as they are recursively fed
58 // back to the projection mechanism.
59 expand && subscriber.next(value as any);
60
61 // Increment the number of active subscriptions so we can track it
62 // against our concurrency limit later.
63 active++;
64
65 // A flag used to show that the inner observable completed.
66 // This is checked during finalization to see if we should
67 // move to the next item in the buffer, if there is on.
68 let innerComplete = false;
69
70 // Start our inner subscription.
71 innerFrom(project(value, index++)).subscribe(
72 createOperatorSubscriber(
73 subscriber,
74 (innerValue) => {
75 // `mergeScan` has additional handling here. For example
76 // taking the inner value and updating state.
77 onBeforeNext?.(innerValue);
78
79 if (expand) {
80 // If we're expanding, then just recurse back to our outer
81 // handler. It will emit the value first thing.
82 outerNext(innerValue as any);
83 } else {
84 // Otherwise, emit the inner value.
85 subscriber.next(innerValue);
86 }
87 },
88 () => {
89 // Flag that we have completed, so we know to check the buffer
90 // during finalization.
91 innerComplete = true;
92 },
93 // Errors are passed to the destination.
94 undefined,
95 () => {
96 // During finalization, if the inner completed (it wasn't errored or
97 // cancelled), then we want to try the next item in the buffer if
98 // there is one.
99 if (innerComplete) {
100 // We have to wrap this in a try/catch because it happens during
101 // finalization, possibly asynchronously, and we want to pass
102 // any errors that happen (like in a projection function) to
103 // the outer Subscriber.
104 try {
105 // INNER SOURCE COMPLETE
106 // Decrement the active count to ensure that the next time
107 // we try to call `doInnerSub`, the number is accurate.
108 active--;
109 // If we have more values in the buffer, try to process those
110 // Note that this call will increment `active` ahead of the
111 // next conditional, if there were any more inner subscriptions
112 // to start.
113 while (buffer.length && active < concurrent) {
114 const bufferedValue = buffer.shift()!;
115 // Particularly for `expand`, we need to check to see if a scheduler was provided
116 // for when we want to start our inner subscription. Otherwise, we just start
117 // are next inner subscription.
118 if (innerSubScheduler) {
119 executeSchedule(subscriber, innerSubScheduler, () => doInnerSub(bufferedValue));
120 } else {
121 doInnerSub(bufferedValue);
122 }
123 }
124 // Check to see if we can complete, and complete if so.
125 checkComplete();
126 } catch (err) {
127 subscriber.error(err);
128 }
129 }
130 }
131 )
132 );
133 };
134
135 // Subscribe to our source observable.
136 source.subscribe(
137 createOperatorSubscriber(subscriber, outerNext, () => {
138 // Outer completed, make a note of it, and check to see if we can complete everything.
139 isComplete = true;
140 checkComplete();
141 })
142 );
143
144 // Additional finalization (for when the destination is torn down).
145 // Other finalization is added implicitly via subscription above.
146 return () => {
147 additionalFinalizer?.();
148 };
149 }