d0ade44d223ac7afe3e625e958cdff1ed1bcc017337d83d9b8e2f646a2552c85c21cbb7599f2beb5afa1e4d6a211fb20978f33e42eee83b8edab86927c828a 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';
  2. import { switchMap } from './switchMap';
  3. import { identity } from '../util/identity';
  4. /**
  5. * Converts a higher-order Observable into a first-order Observable
  6. * producing values only from the most recent observable sequence
  7. *
  8. * <span class="informal">Flattens an Observable-of-Observables.</span>
  9. *
  10. * ![](switchAll.png)
  11. *
  12. * `switchAll` subscribes to a source that is an observable of observables, also known as a
  13. * "higher-order observable" (or `Observable<Observable<T>>`). It subscribes to the most recently
  14. * provided "inner observable" emitted by the source, unsubscribing from any previously subscribed
  15. * to inner observable, such that only the most recent inner observable may be subscribed to at
  16. * any point in time. The resulting observable returned by `switchAll` will only complete if the
  17. * source observable completes, *and* any currently subscribed to inner observable also has completed,
  18. * if there are any.
  19. *
  20. * ## Examples
  21. *
  22. * Spawn a new interval observable for each click event, but for every new
  23. * click, cancel the previous interval and subscribe to the new one
  24. *
  25. * ```ts
  26. * import { fromEvent, tap, map, interval, switchAll } from 'rxjs';
  27. *
  28. * const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click')));
  29. * const source = clicks.pipe(map(() => interval(1000)));
  30. *
  31. * source
  32. * .pipe(switchAll())
  33. * .subscribe(x => console.log(x));
  34. *
  35. * // Output
  36. * // click
  37. * // 0
  38. * // 1
  39. * // 2
  40. * // 3
  41. * // ...
  42. * // click
  43. * // 0
  44. * // 1
  45. * // 2
  46. * // ...
  47. * // click
  48. * // ...
  49. * ```
  50. *
  51. * @see {@link combineLatestAll}
  52. * @see {@link concatAll}
  53. * @see {@link exhaustAll}
  54. * @see {@link switchMap}
  55. * @see {@link switchMapTo}
  56. * @see {@link mergeAll}
  57. *
  58. * @return A function that returns an Observable that converts a higher-order
  59. * Observable into a first-order Observable producing values only from the most
  60. * recent Observable sequence.
  61. */
  62. export function switchAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {
  63. return switchMap(identity);
  64. }