Debian Codegraph @

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

raw
1 import { Subject } from '../Subject';
2 import { asyncScheduler } from '../scheduler/async';
3 import { Observable } from '../Observable';
4 import { Subscription } from '../Subscription';
5 import { Observer, OperatorFunction, SchedulerLike } from '../types';
6 import { operate } from '../util/lift';
7 import { createOperatorSubscriber } from './OperatorSubscriber';
8 import { arrRemove } from '../util/arrRemove';
9 import { popScheduler } from '../util/args';
10 import { executeSchedule } from '../util/executeSchedule';
11
12 export function windowTime<T>(windowTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, Observable<T>>;
13 export function windowTime<T>(
14 windowTimeSpan: number,
15 windowCreationInterval: number,
16 scheduler?: SchedulerLike
17 ): OperatorFunction<T, Observable<T>>;
18 export function windowTime<T>(
19 windowTimeSpan: number,
20 windowCreationInterval: number | null | void,
21 maxWindowSize: number,
22 scheduler?: SchedulerLike
23 ): OperatorFunction<T, Observable<T>>;
24
25 /**
26 * Branch out the source Observable values as a nested Observable periodically
27 * in time.
28 *
29 * <span class="informal">It's like {@link bufferTime}, but emits a nested
30 * Observable instead of an array.</span>
31 *
32 * ![](windowTime.png)
33 *
34 * Returns an Observable that emits windows of items it collects from the source
35 * Observable. The output Observable starts a new window periodically, as
36 * determined by the `windowCreationInterval` argument. It emits each window
37 * after a fixed timespan, specified by the `windowTimeSpan` argument. When the
38 * source Observable completes or encounters an error, the output Observable
39 * emits the current window and propagates the notification from the source
40 * Observable. If `windowCreationInterval` is not provided, the output
41 * Observable starts a new window when the previous window of duration
42 * `windowTimeSpan` completes. If `maxWindowCount` is provided, each window
43 * will emit at most fixed number of values. Window will complete immediately
44 * after emitting last value and next one still will open as specified by
45 * `windowTimeSpan` and `windowCreationInterval` arguments.
46 *
47 * ## Examples
48 *
49 * In every window of 1 second each, emit at most 2 click events
50 *
51 * ```ts
52 * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs';
53 *
54 * const clicks = fromEvent(document, 'click');
55 * const result = clicks.pipe(
56 * windowTime(1000),
57 * map(win => win.pipe(take(2))), // take at most 2 emissions from each window
58 * mergeAll() // flatten the Observable-of-Observables
59 * );
60 * result.subscribe(x => console.log(x));
61 * ```
62 *
63 * Every 5 seconds start a window 1 second long, and emit at most 2 click events per window
64 *
65 * ```ts
66 * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs';
67 *
68 * const clicks = fromEvent(document, 'click');
69 * const result = clicks.pipe(
70 * windowTime(1000, 5000),
71 * map(win => win.pipe(take(2))), // take at most 2 emissions from each window
72 * mergeAll() // flatten the Observable-of-Observables
73 * );
74 * result.subscribe(x => console.log(x));
75 * ```
76 *
77 * Same as example above but with `maxWindowCount` instead of `take`
78 *
79 * ```ts
80 * import { fromEvent, windowTime, mergeAll } from 'rxjs';
81 *
82 * const clicks = fromEvent(document, 'click');
83 * const result = clicks.pipe(
84 * windowTime(1000, 5000, 2), // take at most 2 emissions from each window
85 * mergeAll() // flatten the Observable-of-Observables
86 * );
87 * result.subscribe(x => console.log(x));
88 * ```
89 *
90 * @see {@link window}
91 * @see {@link windowCount}
92 * @see {@link windowToggle}
93 * @see {@link windowWhen}
94 * @see {@link bufferTime}
95 *
96 * @param windowTimeSpan The amount of time, in milliseconds, to fill each window.
97 * @param windowCreationInterval The interval at which to start new
98 * windows.
99 * @param maxWindowSize Max number of
100 * values each window can emit before completion.
101 * @param scheduler The scheduler on which to schedule the
102 * intervals that determine window boundaries.
103 * @return A function that returns an Observable of windows, which in turn are
104 * Observables.
105 */
106 export function windowTime<T>(windowTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, Observable<T>> {
107 const scheduler = popScheduler(otherArgs) ?? asyncScheduler;
108 const windowCreationInterval = (otherArgs[0] as number) ?? null;
109 const maxWindowSize = (otherArgs[1] as number) || Infinity;
110
111 return operate((source, subscriber) => {
112 // The active windows, their related subscriptions, and removal functions.
113 let windowRecords: WindowRecord<T>[] | null = [];
114 // If true, it means that every time we close a window, we want to start a new window.
115 // This is only really used for when *just* the time span is passed.
116 let restartOnClose = false;
117
118 const closeWindow = (record: { window: Subject<T>; subs: Subscription }) => {
119 const { window, subs } = record;
120 window.complete();
121 subs.unsubscribe();
122 arrRemove(windowRecords, record);
123 restartOnClose && startWindow();
124 };
125
126 /**
127 * Called every time we start a new window. This also does
128 * the work of scheduling the job to close the window.
129 */
130 const startWindow = () => {
131 if (windowRecords) {
132 const subs = new Subscription();
133 subscriber.add(subs);
134 const window = new Subject<T>();
135 const record = {
136 window,
137 subs,
138 seen: 0,
139 };
140 windowRecords.push(record);
141 subscriber.next(window.asObservable());
142 executeSchedule(subs, scheduler, () => closeWindow(record), windowTimeSpan);
143 }
144 };
145
146 if (windowCreationInterval !== null && windowCreationInterval >= 0) {
147 // The user passed both a windowTimeSpan (required), and a creation interval
148 // That means we need to start new window on the interval, and those windows need
149 // to wait the required time span before completing.
150 executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);
151 } else {
152 restartOnClose = true;
153 }
154
155 startWindow();
156
157 /**
158 * We need to loop over a copy of the window records several times in this operator.
159 * This is to save bytes over the wire more than anything.
160 * The reason we copy the array is that reentrant code could mutate the array while
161 * we are iterating over it.
162 */
163 const loop = (cb: (record: WindowRecord<T>) => void) => windowRecords!.slice().forEach(cb);
164
165 /**
166 * Used to notify all of the windows and the subscriber in the same way
167 * in the error and complete handlers.
168 */
169 const terminate = (cb: (consumer: Observer<any>) => void) => {
170 loop(({ window }) => cb(window));
171 cb(subscriber);
172 subscriber.unsubscribe();
173 };
174
175 source.subscribe(
176 createOperatorSubscriber(
177 subscriber,
178 (value: T) => {
179 // Notify all windows of the value.
180 loop((record) => {
181 record.window.next(value);
182 // If the window is over the max size, we need to close it.
183 maxWindowSize <= ++record.seen && closeWindow(record);
184 });
185 },
186 // Complete the windows and the downstream subscriber and clean up.
187 () => terminate((consumer) => consumer.complete()),
188 // Notify the windows and the downstream subscriber of the error and clean up.
189 (err) => terminate((consumer) => consumer.error(err))
190 )
191 );
192
193 // Additional finalization. This will be called when the
194 // destination tears down. Other finalizations are registered implicitly
195 // above via subscription.
196 return () => {
197 // Ensure that the buffer is released.
198 windowRecords = null!;
199 };
200 });
201 }
202
203 interface WindowRecord<T> {
204 seen: number;
205 window: Subject<T>;
206 subs: Subscription;
207 }