blob: de834ba110c83031274f60ba1f70bc20ce1ceb98 [file] [log] [blame]
import { async } from '../scheduler/async';
import { isDate } from '../util/isDate';
import { Subscriber } from '../Subscriber';
import { Notification } from '../Notification';
export function delay(delay, scheduler = async) {
const absoluteDelay = isDate(delay);
const delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
return (source) => source.lift(new DelayOperator(delayFor, scheduler));
}
class DelayOperator {
constructor(delay, scheduler) {
this.delay = delay;
this.scheduler = scheduler;
}
call(subscriber, source) {
return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
}
}
class DelaySubscriber extends Subscriber {
constructor(destination, delay, scheduler) {
super(destination);
this.delay = delay;
this.scheduler = scheduler;
this.queue = [];
this.active = false;
this.errored = false;
}
static dispatch(state) {
const source = state.source;
const queue = source.queue;
const scheduler = state.scheduler;
const destination = state.destination;
while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
queue.shift().notification.observe(destination);
}
if (queue.length > 0) {
const delay = Math.max(0, queue[0].time - scheduler.now());
this.schedule(state, delay);
}
else {
this.unsubscribe();
source.active = false;
}
}
_schedule(scheduler) {
this.active = true;
const destination = this.destination;
destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
source: this, destination: this.destination, scheduler: scheduler
}));
}
scheduleNotification(notification) {
if (this.errored === true) {
return;
}
const scheduler = this.scheduler;
const message = new DelayMessage(scheduler.now() + this.delay, notification);
this.queue.push(message);
if (this.active === false) {
this._schedule(scheduler);
}
}
_next(value) {
this.scheduleNotification(Notification.createNext(value));
}
_error(err) {
this.errored = true;
this.queue = [];
this.destination.error(err);
this.unsubscribe();
}
_complete() {
this.scheduleNotification(Notification.createComplete());
this.unsubscribe();
}
}
class DelayMessage {
constructor(time, notification) {
this.time = time;
this.notification = notification;
}
}
//# sourceMappingURL=delay.js.map