Debian Codegraph @

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

raw
1 import { asyncScheduler } from '../scheduler/async';
2 import { Subscription } from '../Subscription';
3 import { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike } from '../types';
4 import { operate } from '../util/lift';
5 import { createOperatorSubscriber } from './OperatorSubscriber';
6
7 /**
8 * Emits a notification from the source Observable only after a particular time span
9 * has passed without another source emission.
10 *
11 * <span class="informal">It's like {@link delay}, but passes only the most
12 * recent notification from each burst of emissions.</span>
13 *
14 * ![](debounceTime.png)
15 *
16 * `debounceTime` delays notifications emitted by the source Observable, but drops
17 * previous pending delayed emissions if a new notification arrives on the source
18 * Observable. This operator keeps track of the most recent notification from the
19 * source Observable, and emits that only when `dueTime` has passed
20 * without any other notification appearing on the source Observable. If a new value
21 * appears before `dueTime` silence occurs, the previous notification will be dropped
22 * and will not be emitted and a new `dueTime` is scheduled.
23 * If the completing event happens during `dueTime` the last cached notification
24 * is emitted before the completion event is forwarded to the output observable.
25 * If the error event happens during `dueTime` or after it only the error event is
26 * forwarded to the output observable. The cache notification is not emitted in this case.
27 *
28 * This is a rate-limiting operator, because it is impossible for more than one
29 * notification to be emitted in any time window of duration `dueTime`, but it is also
30 * a delay-like operator since output emissions do not occur at the same time as
31 * they did on the source Observable. Optionally takes a {@link SchedulerLike} for
32 * managing timers.
33 *
34 * ## Example
35 *
36 * Emit the most recent click after a burst of clicks
37 *
38 * ```ts
39 * import { fromEvent, debounceTime } from 'rxjs';
40 *
41 * const clicks = fromEvent(document, 'click');
42 * const result = clicks.pipe(debounceTime(1000));
43 * result.subscribe(x => console.log(x));
44 * ```
45 *
46 * @see {@link audit}
47 * @see {@link auditTime}
48 * @see {@link debounce}
49 * @see {@link sample}
50 * @see {@link sampleTime}
51 * @see {@link throttle}
52 * @see {@link throttleTime}
53 *
54 * @param dueTime The timeout duration in milliseconds (or the time unit determined
55 * internally by the optional `scheduler`) for the window of time required to wait
56 * for emission silence before emitting the most recent source value.
57 * @param scheduler The {@link SchedulerLike} to use for managing the timers that
58 * handle the timeout for each value.
59 * @return A function that returns an Observable that delays the emissions of
60 * the source Observable by the specified `dueTime`, and may drop some values
61 * if they occur too frequently.
62 */
63 export function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {
64 return operate((source, subscriber) => {
65 let activeTask: Subscription | null = null;
66 let lastValue: T | null = null;
67 let lastTime: number | null = null;
68
69 const emit = () => {
70 if (activeTask) {
71 // We have a value! Free up memory first, then emit the value.
72 activeTask.unsubscribe();
73 activeTask = null;
74 const value = lastValue!;
75 lastValue = null;
76 subscriber.next(value);
77 }
78 };
79 function emitWhenIdle(this: SchedulerAction<unknown>) {
80 // This is called `dueTime` after the first value
81 // but we might have received new values during this window!
82
83 const targetTime = lastTime! + dueTime;
84 const now = scheduler.now();
85 if (now < targetTime) {
86 // On that case, re-schedule to the new target
87 activeTask = this.schedule(undefined, targetTime - now);
88 subscriber.add(activeTask);
89 return;
90 }
91
92 emit();
93 }
94
95 source.subscribe(
96 createOperatorSubscriber(
97 subscriber,
98 (value: T) => {
99 lastValue = value;
100 lastTime = scheduler.now();
101
102 // Only set up a task if it's not already up
103 if (!activeTask) {
104 activeTask = scheduler.schedule(emitWhenIdle, dueTime);
105 subscriber.add(activeTask);
106 }
107 },
108 () => {
109 // Source completed.
110 // Emit any pending debounced values then complete
111 emit();
112 subscriber.complete();
113 },
114 // Pass all errors through to consumer.
115 undefined,
116 () => {
117 // Finalization.
118 lastValue = activeTask = null;
119 }
120 )
121 );
122 });
123 }