/
debounceAfter.ts
67 lines (63 loc) · 1.63 KB
/
debounceAfter.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* @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 {
concat,
MonoTypeOperatorFunction,
Observable,
of,
SchedulerLike,
} from "rxjs";
import {
concatMap,
delay,
distinctUntilChanged,
filter,
publish,
startWith,
switchMap,
takeLast,
takeUntil,
} from "rxjs/operators";
export function debounceAfter<T>(
notifier: Observable<any>,
duration: number,
scheduler?: SchedulerLike
): MonoTypeOperatorFunction<T> {
// https://stackoverflow.com/a/44257656/6680611
return (source: Observable<T>) =>
source.pipe(
publish((sharedSource) =>
notifier.pipe(
switchMap(() =>
concat(of(true), of(false).pipe(delay(duration, scheduler)))
),
startWith(false),
distinctUntilChanged(),
publish((sharedSignal: Observable<boolean>) =>
sharedSignal.pipe(
concatMap((signalled: boolean) =>
signalled
? sharedSource.pipe(
takeUntil(
sharedSignal.pipe(
filter((signalled: boolean) => !signalled)
)
),
takeLast(1)
)
: sharedSource.pipe(
takeUntil(
sharedSignal.pipe(
filter((signalled: boolean) => signalled)
)
)
)
)
)
)
)
)
);
}