Debian Codegraph @

node/rxjs/src/internal/ReplaySubject.ts

raw
1 import { Subject } from './Subject';
2 import { TimestampProvider } from './types';
3 import { Subscriber } from './Subscriber';
4 import { Subscription } from './Subscription';
5 import { dateTimestampProvider } from './scheduler/dateTimestampProvider';
6
7 /**
8 * A variant of {@link Subject} that "replays" old values to new subscribers by emitting them when they first subscribe.
9 *
10 * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,
11 * `ReplaySubject` "observes" values by having them passed to its `next` method. When it observes a value, it will store that
12 * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.
13 *
14 * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in
15 * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will
16 * error if it has observed an error.
17 *
18 * There are two main configuration items to be concerned with:
19 *
20 * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.
21 * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.
22 *
23 * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values
24 * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.
25 *
26 * ### Differences with BehaviorSubject
27 *
28 * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:
29 *
30 * 1. `BehaviorSubject` comes "primed" with a single value upon construction.
31 * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.
32 *
33 * @see {@link Subject}
34 * @see {@link BehaviorSubject}
35 * @see {@link shareReplay}
36 */
37 export class ReplaySubject<T> extends Subject<T> {
38 private _buffer: (T | number)[] = [];
39 private _infiniteTimeWindow = true;
40
41 /**
42 * @param _bufferSize The size of the buffer to replay on subscription
43 * @param _windowTime The amount of time the buffered items will stay buffered
44 * @param _timestampProvider An object with a `now()` method that provides the current timestamp. This is used to
45 * calculate the amount of time something has been buffered.
46 */
47 constructor(
48 private _bufferSize = Infinity,
49 private _windowTime = Infinity,
50 private _timestampProvider: TimestampProvider = dateTimestampProvider
51 ) {
52 super();
53 this._infiniteTimeWindow = _windowTime === Infinity;
54 this._bufferSize = Math.max(1, _bufferSize);
55 this._windowTime = Math.max(1, _windowTime);
56 }
57
58 next(value: T): void {
59 const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;
60 if (!isStopped) {
61 _buffer.push(value);
62 !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
63 }
64 this._trimBuffer();
65 super.next(value);
66 }
67
68 /** @internal */
69 protected _subscribe(subscriber: Subscriber<T>): Subscription {
70 this._throwIfClosed();
71 this._trimBuffer();
72
73 const subscription = this._innerSubscribe(subscriber);
74
75 const { _infiniteTimeWindow, _buffer } = this;
76 // We use a copy here, so reentrant code does not mutate our array while we're
77 // emitting it to a new subscriber.
78 const copy = _buffer.slice();
79 for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
80 subscriber.next(copy[i] as T);
81 }
82
83 this._checkFinalizedStatuses(subscriber);
84
85 return subscription;
86 }
87
88 private _trimBuffer() {
89 const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;
90 // If we don't have an infinite buffer size, and we're over the length,
91 // use splice to truncate the old buffer values off. Note that we have to
92 // double the size for instances where we're not using an infinite time window
93 // because we're storing the values and the timestamps in the same array.
94 const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
95 _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
96
97 // Now, if we're not in an infinite time window, remove all values where the time is
98 // older than what is allowed.
99 if (!_infiniteTimeWindow) {
100 const now = _timestampProvider.now();
101 let last = 0;
102 // Search the array for the first timestamp that isn't expired and
103 // truncate the buffer up to that point.
104 for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {
105 last = i;
106 }
107 last && _buffer.splice(0, last + 1);
108 }
109 }
110 }