889c42331b32c60605f3639732ac0f7804f1c515e0e1b3ebac537cf2e0cd582de4dbb7d7f672254a11d6f736a9434c59151bb43caae03725c9ba5e0d102516 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { observeNotification } from '../Notification';
  2. import { OperatorFunction, ObservableNotification, ValueFromNotification } from '../types';
  3. import { operate } from '../util/lift';
  4. import { createOperatorSubscriber } from './OperatorSubscriber';
  5. /**
  6. * Converts an Observable of {@link ObservableNotification} objects into the emissions
  7. * that they represent.
  8. *
  9. * <span class="informal">Unwraps {@link ObservableNotification} objects as actual `next`,
  10. * `error` and `complete` emissions. The opposite of {@link materialize}.</span>
  11. *
  12. * ![](dematerialize.png)
  13. *
  14. * `dematerialize` is assumed to operate an Observable that only emits
  15. * {@link ObservableNotification} objects as `next` emissions, and does not emit any
  16. * `error`. Such Observable is the output of a `materialize` operation. Those
  17. * notifications are then unwrapped using the metadata they contain, and emitted
  18. * as `next`, `error`, and `complete` on the output Observable.
  19. *
  20. * Use this operator in conjunction with {@link materialize}.
  21. *
  22. * ## Example
  23. *
  24. * Convert an Observable of Notifications to an actual Observable
  25. *
  26. * ```ts
  27. * import { NextNotification, ErrorNotification, of, dematerialize } from 'rxjs';
  28. *
  29. * const notifA: NextNotification<string> = { kind: 'N', value: 'A' };
  30. * const notifB: NextNotification<string> = { kind: 'N', value: 'B' };
  31. * const notifE: ErrorNotification = { kind: 'E', error: new TypeError('x.toUpperCase is not a function') };
  32. *
  33. * const materialized = of(notifA, notifB, notifE);
  34. *
  35. * const upperCase = materialized.pipe(dematerialize());
  36. * upperCase.subscribe({
  37. * next: x => console.log(x),
  38. * error: e => console.error(e)
  39. * });
  40. *
  41. * // Results in:
  42. * // A
  43. * // B
  44. * // TypeError: x.toUpperCase is not a function
  45. * ```
  46. *
  47. * @see {@link materialize}
  48. *
  49. * @return A function that returns an Observable that emits items and
  50. * notifications embedded in Notification objects emitted by the source
  51. * Observable.
  52. */
  53. export function dematerialize<N extends ObservableNotification<any>>(): OperatorFunction<N, ValueFromNotification<N>> {
  54. return operate((source, subscriber) => {
  55. source.subscribe(createOperatorSubscriber(subscriber, (notification) => observeNotification(notification, subscriber)));
  56. });
  57. }