Debian Codegraph @

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

raw
1 import { Subscriber } from '../Subscriber';
2 import { Observable } from '../Observable';
3 import { Subject } from '../Subject';
4 import { ObservableInput, OperatorFunction } from '../types';
5 import { operate } from '../util/lift';
6 import { createOperatorSubscriber } from './OperatorSubscriber';
7 import { innerFrom } from '../observable/innerFrom';
8
9 /**
10 * Branch out the source Observable values as a nested Observable using a
11 * factory function of closing Observables to determine when to start a new
12 * window.
13 *
14 * <span class="informal">It's like {@link bufferWhen}, but emits a nested
15 * Observable instead of an array.</span>
16 *
17 * ![](windowWhen.png)
18 *
19 * Returns an Observable that emits windows of items it collects from the source
20 * Observable. The output Observable emits connected, non-overlapping windows.
21 * It emits the current window and opens a new one whenever the Observable
22 * produced by the specified `closingSelector` function emits an item. The first
23 * window is opened immediately when subscribing to the output Observable.
24 *
25 * ## Example
26 *
27 * Emit only the first two clicks events in every window of [1-5] random seconds
28 *
29 * ```ts
30 * import { fromEvent, windowWhen, interval, map, take, mergeAll } from 'rxjs';
31 *
32 * const clicks = fromEvent(document, 'click');
33 * const result = clicks.pipe(
34 * windowWhen(() => interval(1000 + Math.random() * 4000)),
35 * map(win => win.pipe(take(2))), // take at most 2 emissions from each window
36 * mergeAll() // flatten the Observable-of-Observables
37 * );
38 * result.subscribe(x => console.log(x));
39 * ```
40 *
41 * @see {@link window}
42 * @see {@link windowCount}
43 * @see {@link windowTime}
44 * @see {@link windowToggle}
45 * @see {@link bufferWhen}
46 *
47 * @param closingSelector A function that takes no arguments and returns an
48 * {@link ObservableInput} (that gets converted to Observable) that signals
49 * (on either `next` or `complete`) when to close the previous window and
50 * start a new one.
51 * @return A function that returns an Observable of windows, which in turn are
52 * Observables.
53 */
54 export function windowWhen<T>(closingSelector: () => ObservableInput<any>): OperatorFunction<T, Observable<T>> {
55 return operate((source, subscriber) => {
56 let window: Subject<T> | null;
57 let closingSubscriber: Subscriber<any> | undefined;
58
59 /**
60 * When we get an error, we have to notify both the
61 * destination subscriber and the window.
62 */
63 const handleError = (err: any) => {
64 window!.error(err);
65 subscriber.error(err);
66 };
67
68 /**
69 * Called every time we need to open a window.
70 * Recursive, as it will start the closing notifier, which
71 * inevitably *should* call openWindow -- but may not if
72 * it is a "never" observable.
73 */
74 const openWindow = () => {
75 // We need to clean up our closing subscription,
76 // we only cared about the first next or complete notification.
77 closingSubscriber?.unsubscribe();
78
79 // Close our window before starting a new one.
80 window?.complete();
81
82 // Start the new window.
83 window = new Subject<T>();
84 subscriber.next(window.asObservable());
85
86 // Get our closing notifier.
87 let closingNotifier: Observable<any>;
88 try {
89 closingNotifier = innerFrom(closingSelector());
90 } catch (err) {
91 handleError(err);
92 return;
93 }
94
95 // Subscribe to the closing notifier, be sure
96 // to capture the subscriber (aka Subscription)
97 // so we can clean it up when we close the window
98 // and open a new one.
99 closingNotifier.subscribe((closingSubscriber = createOperatorSubscriber(subscriber, openWindow, openWindow, handleError)));
100 };
101
102 // Start the first window.
103 openWindow();
104
105 // Subscribe to the source
106 source.subscribe(
107 createOperatorSubscriber(
108 subscriber,
109 (value) => window!.next(value),
110 () => {
111 // The source completed, close the window and complete.
112 window!.complete();
113 subscriber.complete();
114 },
115 handleError,
116 () => {
117 // Be sure to clean up our closing subscription
118 // when this tears down.
119 closingSubscriber?.unsubscribe();
120 window = null!;
121 }
122 )
123 );
124 });
125 }