4984089fc62f1d605aa8f071338ca7e4be5eb61156deb7b8d6ec498bc77a1a7f3f8de679ce93ed9eaf20962899da1f1902272563be76f73a9f0394e03d1275 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { MonoTypeOperatorFunction } from '../types';
  2. import { operate } from '../util/lift';
  3. /**
  4. * Returns an Observable that mirrors the source Observable, but will call a specified function when
  5. * the source terminates on complete or error.
  6. * The specified function will also be called when the subscriber explicitly unsubscribes.
  7. *
  8. * ## Examples
  9. *
  10. * Execute callback function when the observable completes
  11. *
  12. * ```ts
  13. * import { interval, take, finalize } from 'rxjs';
  14. *
  15. * // emit value in sequence every 1 second
  16. * const source = interval(1000);
  17. * const example = source.pipe(
  18. * take(5), //take only the first 5 values
  19. * finalize(() => console.log('Sequence complete')) // Execute when the observable completes
  20. * );
  21. * const subscribe = example.subscribe(val => console.log(val));
  22. *
  23. * // results:
  24. * // 0
  25. * // 1
  26. * // 2
  27. * // 3
  28. * // 4
  29. * // 'Sequence complete'
  30. * ```
  31. *
  32. * Execute callback function when the subscriber explicitly unsubscribes
  33. *
  34. * ```ts
  35. * import { interval, finalize, tap, noop, timer } from 'rxjs';
  36. *
  37. * const source = interval(100).pipe(
  38. * finalize(() => console.log('[finalize] Called')),
  39. * tap({
  40. * next: () => console.log('[next] Called'),
  41. * error: () => console.log('[error] Not called'),
  42. * complete: () => console.log('[tap complete] Not called')
  43. * })
  44. * );
  45. *
  46. * const sub = source.subscribe({
  47. * next: x => console.log(x),
  48. * error: noop,
  49. * complete: () => console.log('[complete] Not called')
  50. * });
  51. *
  52. * timer(150).subscribe(() => sub.unsubscribe());
  53. *
  54. * // results:
  55. * // '[next] Called'
  56. * // 0
  57. * // '[finalize] Called'
  58. * ```
  59. *
  60. * @param callback Function to be called when source terminates.
  61. * @return A function that returns an Observable that mirrors the source, but
  62. * will call the specified function on termination.
  63. */
  64. export function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {
  65. return operate((source, subscriber) => {
  66. // TODO: This try/finally was only added for `useDeprecatedSynchronousErrorHandling`.
  67. // REMOVE THIS WHEN THAT HOT GARBAGE IS REMOVED IN V8.
  68. try {
  69. source.subscribe(subscriber);
  70. } finally {
  71. subscriber.add(callback);
  72. }
  73. });
  74. }