2d883a3e62ebbe76690eebb2a145b2d8d00f625ee4e0d035dc05bed6bb32046da22c89b1907560d8d5506875db4db28abdcfe541170f6f4f2a15e7a118d0ef 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import { Subscriber } from '../Subscriber';
  2. import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
  3. import { innerFrom } from '../observable/innerFrom';
  4. import { operate } from '../util/lift';
  5. import { createOperatorSubscriber } from './OperatorSubscriber';
  6. /* tslint:disable:max-line-length */
  7. export function switchMap<T, O extends ObservableInput<any>>(
  8. project: (value: T, index: number) => O
  9. ): OperatorFunction<T, ObservedValueOf<O>>;
  10. /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
  11. export function switchMap<T, O extends ObservableInput<any>>(
  12. project: (value: T, index: number) => O,
  13. resultSelector: undefined
  14. ): OperatorFunction<T, ObservedValueOf<O>>;
  15. /** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
  16. export function switchMap<T, R, O extends ObservableInput<any>>(
  17. project: (value: T, index: number) => O,
  18. resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
  19. ): OperatorFunction<T, R>;
  20. /* tslint:enable:max-line-length */
  21. /**
  22. * Projects each source value to an Observable which is merged in the output
  23. * Observable, emitting values only from the most recently projected Observable.
  24. *
  25. * <span class="informal">Maps each value to an Observable, then flattens all of
  26. * these inner Observables using {@link switchAll}.</span>
  27. *
  28. * ![](switchMap.png)
  29. *
  30. * Returns an Observable that emits items based on applying a function that you
  31. * supply to each item emitted by the source Observable, where that function
  32. * returns an (so-called "inner") Observable. Each time it observes one of these
  33. * inner Observables, the output Observable begins emitting the items emitted by
  34. * that inner Observable. When a new inner Observable is emitted, `switchMap`
  35. * stops emitting items from the earlier-emitted inner Observable and begins
  36. * emitting items from the new one. It continues to behave like this for
  37. * subsequent inner Observables.
  38. *
  39. * ## Example
  40. *
  41. * Generate new Observable according to source Observable values
  42. *
  43. * ```ts
  44. * import { of, switchMap } from 'rxjs';
  45. *
  46. * const switched = of(1, 2, 3).pipe(switchMap(x => of(x, x ** 2, x ** 3)));
  47. * switched.subscribe(x => console.log(x));
  48. * // outputs
  49. * // 1
  50. * // 1
  51. * // 1
  52. * // 2
  53. * // 4
  54. * // 8
  55. * // 3
  56. * // 9
  57. * // 27
  58. * ```
  59. *
  60. * Restart an interval Observable on every click event
  61. *
  62. * ```ts
  63. * import { fromEvent, switchMap, interval } from 'rxjs';
  64. *
  65. * const clicks = fromEvent(document, 'click');
  66. * const result = clicks.pipe(switchMap(() => interval(1000)));
  67. * result.subscribe(x => console.log(x));
  68. * ```
  69. *
  70. * @see {@link concatMap}
  71. * @see {@link exhaustMap}
  72. * @see {@link mergeMap}
  73. * @see {@link switchAll}
  74. * @see {@link switchMapTo}
  75. *
  76. * @param project A function that, when applied to an item emitted by the source
  77. * Observable, returns an Observable.
  78. * @return A function that returns an Observable that emits the result of
  79. * applying the projection function (and the optional deprecated
  80. * `resultSelector`) to each item emitted by the source Observable and taking
  81. * only the values from the most recently projected inner Observable.
  82. */
  83. export function switchMap<T, R, O extends ObservableInput<any>>(
  84. project: (value: T, index: number) => O,
  85. resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
  86. ): OperatorFunction<T, ObservedValueOf<O> | R> {
  87. return operate((source, subscriber) => {
  88. let innerSubscriber: Subscriber<ObservedValueOf<O>> | null = null;
  89. let index = 0;
  90. // Whether or not the source subscription has completed
  91. let isComplete = false;
  92. // We only complete the result if the source is complete AND we don't have an active inner subscription.
  93. // This is called both when the source completes and when the inners complete.
  94. const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();
  95. source.subscribe(
  96. createOperatorSubscriber(
  97. subscriber,
  98. (value) => {
  99. // Cancel the previous inner subscription if there was one
  100. innerSubscriber?.unsubscribe();
  101. let innerIndex = 0;
  102. const outerIndex = index++;
  103. // Start the next inner subscription
  104. innerFrom(project(value, outerIndex)).subscribe(
  105. (innerSubscriber = createOperatorSubscriber(
  106. subscriber,
  107. // When we get a new inner value, next it through. Note that this is
  108. // handling the deprecate result selector here. This is because with this architecture
  109. // it ends up being smaller than using the map operator.
  110. (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue),
  111. () => {
  112. // The inner has completed. Null out the inner subscriber to
  113. // free up memory and to signal that we have no inner subscription
  114. // currently.
  115. innerSubscriber = null!;
  116. checkComplete();
  117. }
  118. ))
  119. );
  120. },
  121. () => {
  122. isComplete = true;
  123. checkComplete();
  124. }
  125. )
  126. );
  127. });
  128. }