/
debounceTimeWithinReason.ts
50 lines (44 loc) · 1.38 KB
/
debounceTimeWithinReason.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* @license Use of this source code is governed by an MIT-style license that
* can be found in the LICENSE file at https://github.com/cartant/rxjs-etc
*/
import {
ConnectableObservable,
merge,
MonoTypeOperatorFunction,
Observable,
SchedulerLike,
Subscription,
timer,
} from "rxjs";
import { debounce, mapTo, publish, startWith, switchMap } from "rxjs/operators";
export function debounceTimeWithinReason<T>(
debounceDuration: number,
reasonableDuration: number,
scheduler?: SchedulerLike
): MonoTypeOperatorFunction<T> {
return (source) =>
source.pipe(
publish(
(sharedSource) =>
new Observable<T>((observer) => {
let reasonableTimer: ConnectableObservable<number>;
const debounced = sharedSource.pipe(
debounce(() =>
merge(timer(debounceDuration, scheduler), reasonableTimer)
)
);
reasonableTimer = debounced.pipe(
mapTo(undefined),
startWith(undefined),
switchMap(() => timer(reasonableDuration, scheduler)),
publish()
) as ConnectableObservable<number>;
const subscription = new Subscription();
subscription.add(reasonableTimer.connect());
subscription.add(debounced.subscribe(observer));
return subscription;
})
)
);
}