Debian Codegraph @

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

raw
1 import { Subscriber } from '../Subscriber';
2 import { MonoTypeOperatorFunction, ObservableInput } from '../types';
3 import { operate } from '../util/lift';
4 import { noop } from '../util/noop';
5 import { createOperatorSubscriber } from './OperatorSubscriber';
6 import { innerFrom } from '../observable/innerFrom';
7
8 /**
9 * Emits a notification from the source Observable only after a particular time span
10 * determined by another Observable has passed without another source emission.
11 *
12 * <span class="informal">It's like {@link debounceTime}, but the time span of
13 * emission silence is determined by a second Observable.</span>
14 *
15 * ![](debounce.svg)
16 *
17 * `debounce` delays notifications emitted by the source Observable, but drops previous
18 * pending delayed emissions if a new notification arrives on the source Observable.
19 * This operator keeps track of the most recent notification from the source
20 * Observable, and spawns a duration Observable by calling the
21 * `durationSelector` function. The notification is emitted only when the duration
22 * Observable emits a next notification, and if no other notification was emitted on
23 * the source Observable since the duration Observable was spawned. If a new
24 * notification appears before the duration Observable emits, the previous notification will
25 * not be emitted and a new duration is scheduled from `durationSelector` is scheduled.
26 * If the completing event happens during the scheduled duration the last cached notification
27 * is emitted before the completion event is forwarded to the output observable.
28 * If the error event happens during the scheduled duration or after it only the error event is
29 * forwarded to the output observable. The cache notification is not emitted in this case.
30 *
31 * Like {@link debounceTime}, this is a rate-limiting operator, and also a
32 * delay-like operator since output emissions do not necessarily occur at the
33 * same time as they did on the source Observable.
34 *
35 * ## Example
36 *
37 * Emit the most recent click after a burst of clicks
38 *
39 * ```ts
40 * import { fromEvent, scan, debounce, interval } from 'rxjs';
41 *
42 * const clicks = fromEvent(document, 'click');
43 * const result = clicks.pipe(
44 * scan(i => ++i, 1),
45 * debounce(i => interval(200 * i))
46 * );
47 * result.subscribe(x => console.log(x));
48 * ```
49 *
50 * @see {@link audit}
51 * @see {@link auditTime}
52 * @see {@link debounceTime}
53 * @see {@link delay}
54 * @see {@link sample}
55 * @see {@link sampleTime}
56 * @see {@link throttle}
57 * @see {@link throttleTime}
58 *
59 * @param durationSelector A function
60 * that receives a value from the source Observable, for computing the timeout
61 * duration for each source value, returned as an Observable or a Promise.
62 * @return A function that returns an Observable that delays the emissions of
63 * the source Observable by the specified duration Observable returned by
64 * `durationSelector`, and may drop some values if they occur too frequently.
65 */
66 export function debounce<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {
67 return operate((source, subscriber) => {
68 let hasValue = false;
69 let lastValue: T | null = null;
70 // The subscriber/subscription for the current debounce, if there is one.
71 let durationSubscriber: Subscriber<any> | null = null;
72
73 const emit = () => {
74 // Unsubscribe any current debounce subscription we have,
75 // we only cared about the first notification from it, and we
76 // want to clean that subscription up as soon as possible.
77 durationSubscriber?.unsubscribe();
78 durationSubscriber = null;
79 if (hasValue) {
80 // We have a value! Free up memory first, then emit the value.
81 hasValue = false;
82 const value = lastValue!;
83 lastValue = null;
84 subscriber.next(value);
85 }
86 };
87
88 source.subscribe(
89 createOperatorSubscriber(
90 subscriber,
91 (value: T) => {
92 // Cancel any pending debounce duration. We don't
93 // need to null it out here yet tho, because we're just going
94 // to create another one in a few lines.
95 durationSubscriber?.unsubscribe();
96 hasValue = true;
97 lastValue = value;
98 // Capture our duration subscriber, so we can unsubscribe it when we're notified
99 // and we're going to emit the value.
100 durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);
101 // Subscribe to the duration.
102 innerFrom(durationSelector(value)).subscribe(durationSubscriber);
103 },
104 () => {
105 // Source completed.
106 // Emit any pending debounced values then complete
107 emit();
108 subscriber.complete();
109 },
110 // Pass all errors through to consumer
111 undefined,
112 () => {
113 // Finalization.
114 lastValue = durationSubscriber = null;
115 }
116 )
117 );
118 });
119 }