timeout.js 2.8 KB

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