timeout.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { asyncScheduler } from '../scheduler/async';
  2. import { isValidDate } from '../util/isDate';
  3. import { operate } from '../util/lift';
  4. import { innerFrom } from '../observable/innerFrom';
  5. import { createErrorClass } from '../util/createErrorClass';
  6. import { createOperatorSubscriber } from './OperatorSubscriber';
  7. import { executeSchedule } from '../util/executeSchedule';
  8. export const TimeoutError = createErrorClass((_super) => function TimeoutErrorImpl(info = null) {
  9. _super(this);
  10. this.message = 'Timeout has occurred';
  11. this.name = 'TimeoutError';
  12. this.info = info;
  13. });
  14. export function timeout(config, schedulerArg) {
  15. const { first, each, with: _with = timeoutErrorFactory, scheduler = schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : asyncScheduler, meta = null, } = (isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config);
  16. if (first == null && each == null) {
  17. throw new TypeError('No timeout provided.');
  18. }
  19. return operate((source, subscriber) => {
  20. let originalSourceSubscription;
  21. let timerSubscription;
  22. let lastValue = null;
  23. let seen = 0;
  24. const startTimer = (delay) => {
  25. timerSubscription = executeSchedule(subscriber, scheduler, () => {
  26. try {
  27. originalSourceSubscription.unsubscribe();
  28. innerFrom(_with({
  29. meta,
  30. lastValue,
  31. seen,
  32. })).subscribe(subscriber);
  33. }
  34. catch (err) {
  35. subscriber.error(err);
  36. }
  37. }, delay);
  38. };
  39. originalSourceSubscription = source.subscribe(createOperatorSubscriber(subscriber, (value) => {
  40. timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
  41. seen++;
  42. subscriber.next((lastValue = value));
  43. each > 0 && startTimer(each);
  44. }, undefined, undefined, () => {
  45. if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {
  46. timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();
  47. }
  48. lastValue = null;
  49. }));
  50. !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler.now()) : each);
  51. });
  52. }
  53. function timeoutErrorFactory(info) {
  54. throw new TimeoutError(info);
  55. }
  56. //# sourceMappingURL=timeout.js.map