Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

throwIfEmpty.ts 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { EmptyError } from '../util/EmptyError';
  2. import { Observable } from '../Observable';
  3. import { Operator } from '../Operator';
  4. import { Subscriber } from '../Subscriber';
  5. import { TeardownLogic, MonoTypeOperatorFunction } from '../types';
  6. /**
  7. * If the source observable completes without emitting a value, it will emit
  8. * an error. The error will be created at that time by the optional
  9. * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.
  10. *
  11. * ![](throwIfEmpty.png)
  12. *
  13. * ## Example
  14. * ```ts
  15. * import { fromEvent, timer } from 'rxjs';
  16. * import { throwIfEmpty, takeUntil } from 'rxjs/operators';
  17. *
  18. * const click$ = fromEvent(document, 'click');
  19. *
  20. * click$.pipe(
  21. * takeUntil(timer(1000)),
  22. * throwIfEmpty(
  23. * () => new Error('the document was not clicked within 1 second')
  24. * ),
  25. * )
  26. * .subscribe({
  27. * next() { console.log('The button was clicked'); },
  28. * error(err) { console.error(err); }
  29. * });
  30. * ```
  31. *
  32. * @param errorFactory A factory function called to produce the
  33. * error to be thrown when the source observable completes without emitting a
  34. * value.
  35. */
  36. export function throwIfEmpty <T>(errorFactory: (() => any) = defaultErrorFactory): MonoTypeOperatorFunction<T> {
  37. return (source: Observable<T>) => {
  38. return source.lift(new ThrowIfEmptyOperator(errorFactory));
  39. };
  40. }
  41. class ThrowIfEmptyOperator<T> implements Operator<T, T> {
  42. constructor(private errorFactory: () => any) {
  43. }
  44. call(subscriber: Subscriber<T>, source: any): TeardownLogic {
  45. return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory));
  46. }
  47. }
  48. class ThrowIfEmptySubscriber<T> extends Subscriber<T> {
  49. private hasValue: boolean = false;
  50. constructor(destination: Subscriber<T>, private errorFactory: () => any) {
  51. super(destination);
  52. }
  53. protected _next(value: T): void {
  54. this.hasValue = true;
  55. this.destination.next(value);
  56. }
  57. protected _complete() {
  58. if (!this.hasValue) {
  59. let err: any;
  60. try {
  61. err = this.errorFactory();
  62. } catch (e) {
  63. err = e;
  64. }
  65. this.destination.error(err);
  66. } else {
  67. return this.destination.complete();
  68. }
  69. }
  70. }
  71. function defaultErrorFactory() {
  72. return new EmptyError();
  73. }