91b124b6a8b13fcfd68270c4a23e97a3f1d041a5e40f3fde4ecb4656d669a769f8bed1ccc4d10096b7d5a8160729ba15203500f6e3b7a1bd8f790539e557aa 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Observable } from '../Observable';
  2. import { SchedulerLike } from '../types';
  3. /**
  4. * A simple Observable that emits no items to the Observer and immediately
  5. * emits a complete notification.
  6. *
  7. * <span class="informal">Just emits 'complete', and nothing else.</span>
  8. *
  9. * ![](empty.png)
  10. *
  11. * A simple Observable that only emits the complete notification. It can be used
  12. * for composing with other Observables, such as in a {@link mergeMap}.
  13. *
  14. * ## Examples
  15. *
  16. * Log complete notification
  17. *
  18. * ```ts
  19. * import { EMPTY } from 'rxjs';
  20. *
  21. * EMPTY.subscribe({
  22. * next: () => console.log('Next'),
  23. * complete: () => console.log('Complete!')
  24. * });
  25. *
  26. * // Outputs
  27. * // Complete!
  28. * ```
  29. *
  30. * Emit the number 7, then complete
  31. *
  32. * ```ts
  33. * import { EMPTY, startWith } from 'rxjs';
  34. *
  35. * const result = EMPTY.pipe(startWith(7));
  36. * result.subscribe(x => console.log(x));
  37. *
  38. * // Outputs
  39. * // 7
  40. * ```
  41. *
  42. * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`
  43. *
  44. * ```ts
  45. * import { interval, mergeMap, of, EMPTY } from 'rxjs';
  46. *
  47. * const interval$ = interval(1000);
  48. * const result = interval$.pipe(
  49. * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),
  50. * );
  51. * result.subscribe(x => console.log(x));
  52. *
  53. * // Results in the following to the console:
  54. * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)
  55. * // x will occur every 1000ms
  56. * // if x % 2 is equal to 1, print a, b, c (each on its own)
  57. * // if x % 2 is not equal to 1, nothing will be output
  58. * ```
  59. *
  60. * @see {@link Observable}
  61. * @see {@link NEVER}
  62. * @see {@link of}
  63. * @see {@link throwError}
  64. */
  65. export const EMPTY = new Observable<never>((subscriber) => subscriber.complete());
  66. /**
  67. * @param scheduler A {@link SchedulerLike} to use for scheduling
  68. * the emission of the complete notification.
  69. * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.
  70. */
  71. export function empty(scheduler?: SchedulerLike) {
  72. return scheduler ? emptyScheduled(scheduler) : EMPTY;
  73. }
  74. function emptyScheduled(scheduler: SchedulerLike) {
  75. return new Observable<never>((subscriber) => scheduler.schedule(() => subscriber.complete()));
  76. }