Debian Codegraph @

node/rxjs/src/internal/operators/bufferTime.ts

raw
1 import { Subscription } from '../Subscription';
2 import { OperatorFunction, SchedulerLike } from '../types';
3 import { operate } from '../util/lift';
4 import { createOperatorSubscriber } from './OperatorSubscriber';
5 import { arrRemove } from '../util/arrRemove';
6 import { asyncScheduler } from '../scheduler/async';
7 import { popScheduler } from '../util/args';
8 import { executeSchedule } from '../util/executeSchedule';
9
10 export function bufferTime<T>(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;
11 export function bufferTime<T>(
12 bufferTimeSpan: number,
13 bufferCreationInterval: number | null | undefined,
14 scheduler?: SchedulerLike
15 ): OperatorFunction<T, T[]>;
16 export function bufferTime<T>(
17 bufferTimeSpan: number,
18 bufferCreationInterval: number | null | undefined,
19 maxBufferSize: number,
20 scheduler?: SchedulerLike
21 ): OperatorFunction<T, T[]>;
22
23 /**
24 * Buffers the source Observable values for a specific time period.
25 *
26 * <span class="informal">Collects values from the past as an array, and emits
27 * those arrays periodically in time.</span>
28 *
29 * ![](bufferTime.png)
30 *
31 * Buffers values from the source for a specific time duration `bufferTimeSpan`.
32 * Unless the optional argument `bufferCreationInterval` is given, it emits and
33 * resets the buffer every `bufferTimeSpan` milliseconds. If
34 * `bufferCreationInterval` is given, this operator opens the buffer every
35 * `bufferCreationInterval` milliseconds and closes (emits and resets) the
36 * buffer every `bufferTimeSpan` milliseconds. When the optional argument
37 * `maxBufferSize` is specified, the buffer will be closed either after
38 * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.
39 *
40 * ## Examples
41 *
42 * Every second, emit an array of the recent click events
43 *
44 * ```ts
45 * import { fromEvent, bufferTime } from 'rxjs';
46 *
47 * const clicks = fromEvent(document, 'click');
48 * const buffered = clicks.pipe(bufferTime(1000));
49 * buffered.subscribe(x => console.log(x));
50 * ```
51 *
52 * Every 5 seconds, emit the click events from the next 2 seconds
53 *
54 * ```ts
55 * import { fromEvent, bufferTime } from 'rxjs';
56 *
57 * const clicks = fromEvent(document, 'click');
58 * const buffered = clicks.pipe(bufferTime(2000, 5000));
59 * buffered.subscribe(x => console.log(x));
60 * ```
61 *
62 * @see {@link buffer}
63 * @see {@link bufferCount}
64 * @see {@link bufferToggle}
65 * @see {@link bufferWhen}
66 * @see {@link windowTime}
67 *
68 * @param bufferTimeSpan The amount of time to fill each buffer array.
69 * @param otherArgs Other configuration arguments such as:
70 * - `bufferCreationInterval` - the interval at which to start new buffers;
71 * - `maxBufferSize` - the maximum buffer size;
72 * - `scheduler` - the scheduler on which to schedule the intervals that determine buffer boundaries.
73 * @return A function that returns an Observable of arrays of buffered values.
74 */
75 export function bufferTime<T>(bufferTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, T[]> {
76 const scheduler = popScheduler(otherArgs) ?? asyncScheduler;
77 const bufferCreationInterval = (otherArgs[0] as number) ?? null;
78 const maxBufferSize = (otherArgs[1] as number) || Infinity;
79
80 return operate((source, subscriber) => {
81 // The active buffers, their related subscriptions, and removal functions.
82 let bufferRecords: { buffer: T[]; subs: Subscription }[] | null = [];
83 // If true, it means that every time we emit a buffer, we want to start a new buffer
84 // this is only really used for when *just* the buffer time span is passed.
85 let restartOnEmit = false;
86
87 /**
88 * Does the work of emitting the buffer from the record, ensuring that the
89 * record is removed before the emission so reentrant code (from some custom scheduling, perhaps)
90 * does not alter the buffer. Also checks to see if a new buffer needs to be started
91 * after the emit.
92 */
93 const emit = (record: { buffer: T[]; subs: Subscription }) => {
94 const { buffer, subs } = record;
95 subs.unsubscribe();
96 arrRemove(bufferRecords, record);
97 subscriber.next(buffer);
98 restartOnEmit && startBuffer();
99 };
100
101 /**
102 * Called every time we start a new buffer. This does
103 * the work of scheduling a job at the requested bufferTimeSpan
104 * that will emit the buffer (if it's not unsubscribed before then).
105 */
106 const startBuffer = () => {
107 if (bufferRecords) {
108 const subs = new Subscription();
109 subscriber.add(subs);
110 const buffer: T[] = [];
111 const record = {
112 buffer,
113 subs,
114 };
115 bufferRecords.push(record);
116 executeSchedule(subs, scheduler, () => emit(record), bufferTimeSpan);
117 }
118 };
119
120 if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {
121 // The user passed both a bufferTimeSpan (required), and a creation interval
122 // That means we need to start new buffers on the interval, and those buffers need
123 // to wait the required time span before emitting.
124 executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);
125 } else {
126 restartOnEmit = true;
127 }
128
129 startBuffer();
130
131 const bufferTimeSubscriber = createOperatorSubscriber(
132 subscriber,
133 (value: T) => {
134 // Copy the records, so if we need to remove one we
135 // don't mutate the array. It's hard, but not impossible to
136 // set up a buffer time that could mutate the array and
137 // cause issues here.
138 const recordsCopy = bufferRecords!.slice();
139 for (const record of recordsCopy) {
140 // Loop over all buffers and
141 const { buffer } = record;
142 buffer.push(value);
143 // If the buffer is over the max size, we need to emit it.
144 maxBufferSize <= buffer.length && emit(record);
145 }
146 },
147 () => {
148 // The source completed, emit all of the active
149 // buffers we have before we complete.
150 while (bufferRecords?.length) {
151 subscriber.next(bufferRecords.shift()!.buffer);
152 }
153 bufferTimeSubscriber?.unsubscribe();
154 subscriber.complete();
155 subscriber.unsubscribe();
156 },
157 // Pass all errors through to consumer.
158 undefined,
159 // Clean up
160 () => (bufferRecords = null)
161 );
162
163 source.subscribe(bufferTimeSubscriber);
164 });
165 }