-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathrefCountOn.ts
46 lines (43 loc) · 1.07 KB
/
refCountOn.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
/**
* @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,
MonoTypeOperatorFunction,
Observable,
SchedulerLike,
Subscription,
using,
} from "rxjs";
export function refCountOn<T>(
scheduler: SchedulerLike
): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => {
const connectable: ConnectableObservable<T> = source as any;
let count = 0;
let subscription: Subscription | null = null;
return using(
() => {
++count;
scheduler.schedule(() => {
if (!subscription && count > 0) {
subscription = connectable.connect();
}
});
return {
unsubscribe: () => {
--count;
scheduler.schedule(() => {
if (subscription && count === 0) {
subscription.unsubscribe();
subscription = null;
}
});
},
};
},
() => source
);
};
}