c1d806a8235128a66a6f0cc1bb9aebf6e12ca78f28ac45ad63770abb2097b236ef3b7240a815c4dcc36e7572d3652cfef031d62a7cbe4e66c97cd86faffa5f 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { EmptyError } from '../util/EmptyError';
  2. import { MonoTypeOperatorFunction } from '../types';
  3. import { operate } from '../util/lift';
  4. import { createOperatorSubscriber } from './OperatorSubscriber';
  5. /**
  6. * If the source observable completes without emitting a value, it will emit
  7. * an error. The error will be created at that time by the optional
  8. * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.
  9. *
  10. * ![](throwIfEmpty.png)
  11. *
  12. * ## Example
  13. *
  14. * Throw an error if the document wasn't clicked within 1 second
  15. *
  16. * ```ts
  17. * import { fromEvent, takeUntil, timer, throwIfEmpty } from 'rxjs';
  18. *
  19. * const click$ = fromEvent(document, 'click');
  20. *
  21. * click$.pipe(
  22. * takeUntil(timer(1000)),
  23. * throwIfEmpty(() => new Error('The document was not clicked within 1 second'))
  24. * )
  25. * .subscribe({
  26. * next() {
  27. * console.log('The document was clicked');
  28. * },
  29. * error(err) {
  30. * console.error(err.message);
  31. * }
  32. * });
  33. * ```
  34. *
  35. * @param errorFactory A factory function called to produce the
  36. * error to be thrown when the source observable completes without emitting a
  37. * value.
  38. * @return A function that returns an Observable that throws an error if the
  39. * source Observable completed without emitting.
  40. */
  41. export function throwIfEmpty<T>(errorFactory: () => any = defaultErrorFactory): MonoTypeOperatorFunction<T> {
  42. return operate((source, subscriber) => {
  43. let hasValue = false;
  44. source.subscribe(
  45. createOperatorSubscriber(
  46. subscriber,
  47. (value) => {
  48. hasValue = true;
  49. subscriber.next(value);
  50. },
  51. () => (hasValue ? subscriber.complete() : subscriber.error(errorFactory()))
  52. )
  53. );
  54. });
  55. }
  56. function defaultErrorFactory() {
  57. return new EmptyError();
  58. }