-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathtapSubscribe.ts
49 lines (46 loc) · 1.35 KB
/
tapSubscribe.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
/**
* @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 { defer, MonoTypeOperatorFunction, noop } from "rxjs";
import { finalize, tap } from "rxjs/operators";
export interface TapSubscriberConfig {
ignore?: { complete?: boolean; error?: boolean };
subscribe?: () => void;
unsubscribe?: () => void;
}
export function tapSubscribe<T>(
config: TapSubscriberConfig
): MonoTypeOperatorFunction<T>;
export function tapSubscribe<T>(
subscribe: () => void
): MonoTypeOperatorFunction<T>;
export function tapSubscribe<T>(
configOrSubscribe: TapSubscriberConfig | (() => void)
): MonoTypeOperatorFunction<T> {
const { ignore = {}, subscribe = noop, unsubscribe = noop } =
typeof configOrSubscribe === "function"
? { subscribe: configOrSubscribe }
: configOrSubscribe;
return (source) =>
defer(() => {
let completed = false;
let errored = false;
subscribe();
return source.pipe(
tap({
complete: () => (completed = true),
error: () => (errored = true),
}),
finalize(() => {
if (completed && ignore.complete) {
return;
}
if (errored && ignore.error) {
return;
}
unsubscribe();
})
);
});
}