@reactivex/rxjs
Version:
Reactive Extensions for modern JavaScript
67 lines • 2.28 kB
JavaScript
import { Subject } from './Subject';
import { queue } from './scheduler/queue';
import { ObserveOnSubscriber } from './operator/observeOn';
/**
* @class ReplaySubject<T>
*/
export class ReplaySubject extends Subject {
constructor(bufferSize = Number.POSITIVE_INFINITY, windowTime = Number.POSITIVE_INFINITY, scheduler) {
super();
this.events = [];
this.scheduler = scheduler;
this.bufferSize = bufferSize < 1 ? 1 : bufferSize;
this._windowTime = windowTime < 1 ? 1 : windowTime;
}
_next(value) {
const now = this._getNow();
this.events.push(new ReplayEvent(now, value));
this._trimBufferThenGetEvents(now);
super._next(value);
}
_subscribe(subscriber) {
const events = this._trimBufferThenGetEvents(this._getNow());
const scheduler = this.scheduler;
if (scheduler) {
subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler));
}
let index = -1;
const len = events.length;
while (++index < len && !subscriber.isUnsubscribed) {
subscriber.next(events[index].value);
}
return super._subscribe(subscriber);
}
_getNow() {
return (this.scheduler || queue).now();
}
_trimBufferThenGetEvents(now) {
const bufferSize = this.bufferSize;
const _windowTime = this._windowTime;
const events = this.events;
let eventsCount = events.length;
let spliceCount = 0;
// Trim events that fall out of the time window.
// Start at the front of the list. Break early once
// we encounter an event that falls within the window.
while (spliceCount < eventsCount) {
if ((now - events[spliceCount].time) < _windowTime) {
break;
}
spliceCount += 1;
}
if (eventsCount > bufferSize) {
spliceCount = Math.max(spliceCount, eventsCount - bufferSize);
}
if (spliceCount > 0) {
events.splice(0, spliceCount);
}
return events;
}
}
class ReplayEvent {
constructor(time, value) {
this.time = time;
this.value = value;
}
}
//# sourceMappingURL=ReplaySubject.js.map