Notification.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { EMPTY } from './observable/empty';
  2. import { of } from './observable/of';
  3. import { throwError } from './observable/throwError';
  4. import { isFunction } from './util/isFunction';
  5. export var NotificationKind;
  6. (function (NotificationKind) {
  7. NotificationKind["NEXT"] = "N";
  8. NotificationKind["ERROR"] = "E";
  9. NotificationKind["COMPLETE"] = "C";
  10. })(NotificationKind || (NotificationKind = {}));
  11. export class Notification {
  12. constructor(kind, value, error) {
  13. this.kind = kind;
  14. this.value = value;
  15. this.error = error;
  16. this.hasValue = kind === 'N';
  17. }
  18. observe(observer) {
  19. return observeNotification(this, observer);
  20. }
  21. do(nextHandler, errorHandler, completeHandler) {
  22. const { kind, value, error } = this;
  23. return kind === 'N' ? nextHandler === null || nextHandler === void 0 ? void 0 : nextHandler(value) : kind === 'E' ? errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(error) : completeHandler === null || completeHandler === void 0 ? void 0 : completeHandler();
  24. }
  25. accept(nextOrObserver, error, complete) {
  26. var _a;
  27. return isFunction((_a = nextOrObserver) === null || _a === void 0 ? void 0 : _a.next)
  28. ? this.observe(nextOrObserver)
  29. : this.do(nextOrObserver, error, complete);
  30. }
  31. toObservable() {
  32. const { kind, value, error } = this;
  33. const result = kind === 'N'
  34. ?
  35. of(value)
  36. :
  37. kind === 'E'
  38. ?
  39. throwError(() => error)
  40. :
  41. kind === 'C'
  42. ?
  43. EMPTY
  44. :
  45. 0;
  46. if (!result) {
  47. throw new TypeError(`Unexpected notification kind ${kind}`);
  48. }
  49. return result;
  50. }
  51. static createNext(value) {
  52. return new Notification('N', value);
  53. }
  54. static createError(err) {
  55. return new Notification('E', undefined, err);
  56. }
  57. static createComplete() {
  58. return Notification.completeNotification;
  59. }
  60. }
  61. Notification.completeNotification = new Notification('C');
  62. export function observeNotification(notification, observer) {
  63. var _a, _b, _c;
  64. const { kind, value, error } = notification;
  65. if (typeof kind !== 'string') {
  66. throw new TypeError('Invalid notification, missing "kind"');
  67. }
  68. kind === 'N' ? (_a = observer.next) === null || _a === void 0 ? void 0 : _a.call(observer, value) : kind === 'E' ? (_b = observer.error) === null || _b === void 0 ? void 0 : _b.call(observer, error) : (_c = observer.complete) === null || _c === void 0 ? void 0 : _c.call(observer);
  69. }
  70. //# sourceMappingURL=Notification.js.map