mergeMap.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { Observable } from '../Observable';
  2. import { Operator } from '../Operator';
  3. import { Subscriber } from '../Subscriber';
  4. import { Subscription } from '../Subscription';
  5. import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
  6. import { map } from './map';
  7. import { from } from '../observable/from';
  8. import { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';
  9. /* tslint:disable:max-line-length */
  10. export function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;
  11. /** @deprecated resultSelector no longer supported, use inner map instead */
  12. export function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;
  13. /** @deprecated resultSelector no longer supported, use inner map instead */
  14. export function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;
  15. /* tslint:enable:max-line-length */
  16. /**
  17. * Projects each source value to an Observable which is merged in the output
  18. * Observable.
  19. *
  20. * <span class="informal">Maps each value to an Observable, then flattens all of
  21. * these inner Observables using {@link mergeAll}.</span>
  22. *
  23. * ![](mergeMap.png)
  24. *
  25. * Returns an Observable that emits items based on applying a function that you
  26. * supply to each item emitted by the source Observable, where that function
  27. * returns an Observable, and then merging those resulting Observables and
  28. * emitting the results of this merger.
  29. *
  30. * ## Example
  31. * Map and flatten each letter to an Observable ticking every 1 second
  32. * ```ts
  33. * import { of, interval } from 'rxjs';
  34. * import { mergeMap, map } from 'rxjs/operators';
  35. *
  36. * const letters = of('a', 'b', 'c');
  37. * const result = letters.pipe(
  38. * mergeMap(x => interval(1000).pipe(map(i => x+i))),
  39. * );
  40. * result.subscribe(x => console.log(x));
  41. *
  42. * // Results in the following:
  43. * // a0
  44. * // b0
  45. * // c0
  46. * // a1
  47. * // b1
  48. * // c1
  49. * // continues to list a,b,c with respective ascending integers
  50. * ```
  51. *
  52. * @see {@link concatMap}
  53. * @see {@link exhaustMap}
  54. * @see {@link merge}
  55. * @see {@link mergeAll}
  56. * @see {@link mergeMapTo}
  57. * @see {@link mergeScan}
  58. * @see {@link switchMap}
  59. *
  60. * @param {function(value: T, ?index: number): ObservableInput} project A function
  61. * that, when applied to an item emitted by the source Observable, returns an
  62. * Observable.
  63. * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
  64. * Observables being subscribed to concurrently.
  65. * @return {Observable} An Observable that emits the result of applying the
  66. * projection function (and the optional deprecated `resultSelector`) to each item
  67. * emitted by the source Observable and merging the results of the Observables
  68. * obtained from this transformation.
  69. */
  70. export function mergeMap<T, R, O extends ObservableInput<any>>(
  71. project: (value: T, index: number) => O,
  72. resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,
  73. concurrent: number = Number.POSITIVE_INFINITY
  74. ): OperatorFunction<T, ObservedValueOf<O>|R> {
  75. if (typeof resultSelector === 'function') {
  76. // DEPRECATED PATH
  77. return (source: Observable<T>) => source.pipe(
  78. mergeMap((a, i) => from(project(a, i)).pipe(
  79. map((b: any, ii: number) => resultSelector(a, b, i, ii)),
  80. ), concurrent)
  81. );
  82. } else if (typeof resultSelector === 'number') {
  83. concurrent = resultSelector;
  84. }
  85. return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));
  86. }
  87. export class MergeMapOperator<T, R> implements Operator<T, R> {
  88. constructor(private project: (value: T, index: number) => ObservableInput<R>,
  89. private concurrent: number = Number.POSITIVE_INFINITY) {
  90. }
  91. call(observer: Subscriber<R>, source: any): any {
  92. return source.subscribe(new MergeMapSubscriber(
  93. observer, this.project, this.concurrent
  94. ));
  95. }
  96. }
  97. /**
  98. * We need this JSDoc comment for affecting ESDoc.
  99. * @ignore
  100. * @extends {Ignored}
  101. */
  102. export class MergeMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {
  103. private hasCompleted: boolean = false;
  104. private buffer: T[] = [];
  105. private active: number = 0;
  106. protected index: number = 0;
  107. constructor(destination: Subscriber<R>,
  108. private project: (value: T, index: number) => ObservableInput<R>,
  109. private concurrent: number = Number.POSITIVE_INFINITY) {
  110. super(destination);
  111. }
  112. protected _next(value: T): void {
  113. if (this.active < this.concurrent) {
  114. this._tryNext(value);
  115. } else {
  116. this.buffer.push(value);
  117. }
  118. }
  119. protected _tryNext(value: T) {
  120. let result: ObservableInput<R>;
  121. const index = this.index++;
  122. try {
  123. result = this.project(value, index);
  124. } catch (err) {
  125. this.destination.error!(err);
  126. return;
  127. }
  128. this.active++;
  129. this._innerSub(result);
  130. }
  131. private _innerSub(ish: ObservableInput<R>): void {
  132. const innerSubscriber = new SimpleInnerSubscriber(this);
  133. const destination = this.destination as Subscription;
  134. destination.add(innerSubscriber);
  135. const innerSubscription = innerSubscribe(ish, innerSubscriber);
  136. // The returned subscription will usually be the subscriber that was
  137. // passed. However, interop subscribers will be wrapped and for
  138. // unsubscriptions to chain correctly, the wrapper needs to be added, too.
  139. if (innerSubscription !== innerSubscriber) {
  140. destination.add(innerSubscription);
  141. }
  142. }
  143. protected _complete(): void {
  144. this.hasCompleted = true;
  145. if (this.active === 0 && this.buffer.length === 0) {
  146. this.destination.complete!();
  147. }
  148. this.unsubscribe();
  149. }
  150. notifyNext(innerValue: R): void {
  151. this.destination.next!(innerValue);
  152. }
  153. notifyComplete(): void {
  154. const buffer = this.buffer;
  155. this.active--;
  156. if (buffer.length > 0) {
  157. this._next(buffer.shift()!);
  158. } else if (this.active === 0 && this.hasCompleted) {
  159. this.destination.complete!();
  160. }
  161. }
  162. }
  163. /**
  164. * @deprecated renamed. Use {@link mergeMap}
  165. */
  166. export const flatMap = mergeMap;