delay.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import { async } from '../scheduler/async';
  2. import { isDate } from '../util/isDate';
  3. import { Operator } from '../Operator';
  4. import { Subscriber } from '../Subscriber';
  5. import { Subscription } from '../Subscription';
  6. import { Notification } from '../Notification';
  7. import { Observable } from '../Observable';
  8. import { MonoTypeOperatorFunction, PartialObserver, SchedulerAction, SchedulerLike, TeardownLogic } from '../types';
  9. /**
  10. * Delays the emission of items from the source Observable by a given timeout or
  11. * until a given Date.
  12. *
  13. * <span class="informal">Time shifts each item by some specified amount of
  14. * milliseconds.</span>
  15. *
  16. * ![](delay.png)
  17. *
  18. * If the delay argument is a Number, this operator time shifts the source
  19. * Observable by that amount of time expressed in milliseconds. The relative
  20. * time intervals between the values are preserved.
  21. *
  22. * If the delay argument is a Date, this operator time shifts the start of the
  23. * Observable execution until the given date occurs.
  24. *
  25. * ## Examples
  26. * Delay each click by one second
  27. * ```ts
  28. * import { fromEvent } from 'rxjs';
  29. * import { delay } from 'rxjs/operators';
  30. *
  31. * const clicks = fromEvent(document, 'click');
  32. * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second
  33. * delayedClicks.subscribe(x => console.log(x));
  34. * ```
  35. *
  36. * Delay all clicks until a future date happens
  37. * ```ts
  38. * import { fromEvent } from 'rxjs';
  39. * import { delay } from 'rxjs/operators';
  40. *
  41. * const clicks = fromEvent(document, 'click');
  42. * const date = new Date('March 15, 2050 12:00:00'); // in the future
  43. * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date
  44. * delayedClicks.subscribe(x => console.log(x));
  45. * ```
  46. *
  47. * @see {@link debounceTime}
  48. * @see {@link delayWhen}
  49. *
  50. * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
  51. * a `Date` until which the emission of the source items is delayed.
  52. * @param {SchedulerLike} [scheduler=async] The {@link SchedulerLike} to use for
  53. * managing the timers that handle the time-shift for each item.
  54. * @return {Observable} An Observable that delays the emissions of the source
  55. * Observable by the specified timeout or Date.
  56. * @method delay
  57. * @owner Observable
  58. */
  59. export function delay<T>(delay: number|Date,
  60. scheduler: SchedulerLike = async): MonoTypeOperatorFunction<T> {
  61. const absoluteDelay = isDate(delay);
  62. const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(<number>delay);
  63. return (source: Observable<T>) => source.lift(new DelayOperator(delayFor, scheduler));
  64. }
  65. class DelayOperator<T> implements Operator<T, T> {
  66. constructor(private delay: number,
  67. private scheduler: SchedulerLike) {
  68. }
  69. call(subscriber: Subscriber<T>, source: any): TeardownLogic {
  70. return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
  71. }
  72. }
  73. interface DelayState<T> {
  74. source: DelaySubscriber<T>;
  75. destination: PartialObserver<T>;
  76. scheduler: SchedulerLike;
  77. }
  78. /**
  79. * We need this JSDoc comment for affecting ESDoc.
  80. * @ignore
  81. * @extends {Ignored}
  82. */
  83. class DelaySubscriber<T> extends Subscriber<T> {
  84. private queue: Array<DelayMessage<T>> = [];
  85. private active: boolean = false;
  86. private errored: boolean = false;
  87. private static dispatch<T>(this: SchedulerAction<DelayState<T>>, state: DelayState<T>): void {
  88. const source = state.source;
  89. const queue = source.queue;
  90. const scheduler = state.scheduler;
  91. const destination = state.destination;
  92. while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
  93. queue.shift().notification.observe(destination);
  94. }
  95. if (queue.length > 0) {
  96. const delay = Math.max(0, queue[0].time - scheduler.now());
  97. this.schedule(state, delay);
  98. } else {
  99. this.unsubscribe();
  100. source.active = false;
  101. }
  102. }
  103. constructor(destination: Subscriber<T>,
  104. private delay: number,
  105. private scheduler: SchedulerLike) {
  106. super(destination);
  107. }
  108. private _schedule(scheduler: SchedulerLike): void {
  109. this.active = true;
  110. const destination = this.destination as Subscription;
  111. destination.add(scheduler.schedule<DelayState<T>>(DelaySubscriber.dispatch, this.delay, {
  112. source: this, destination: this.destination, scheduler: scheduler
  113. }));
  114. }
  115. private scheduleNotification(notification: Notification<T>): void {
  116. if (this.errored === true) {
  117. return;
  118. }
  119. const scheduler = this.scheduler;
  120. const message = new DelayMessage(scheduler.now() + this.delay, notification);
  121. this.queue.push(message);
  122. if (this.active === false) {
  123. this._schedule(scheduler);
  124. }
  125. }
  126. protected _next(value: T) {
  127. this.scheduleNotification(Notification.createNext(value));
  128. }
  129. protected _error(err: any) {
  130. this.errored = true;
  131. this.queue = [];
  132. this.destination.error(err);
  133. this.unsubscribe();
  134. }
  135. protected _complete() {
  136. this.scheduleNotification(Notification.createComplete());
  137. this.unsubscribe();
  138. }
  139. }
  140. class DelayMessage<T> {
  141. constructor(public readonly time: number,
  142. public readonly notification: Notification<T>) {
  143. }
  144. }