-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
dispose.ts
37 lines (33 loc) · 982 Bytes
/
dispose.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
/**
* @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 {
Observable,
Operator,
OperatorFunction,
Subscriber,
TeardownLogic,
} from "rxjs";
export function dispose<T>(callback: () => void): OperatorFunction<T, T> {
return (source: Observable<T>) => source.lift(new DisposeOperator(callback));
}
class DisposeOperator<T> implements Operator<T, T> {
constructor(private callback: () => void) {}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source.subscribe(new DisposeSubscriber(subscriber, this.callback));
}
}
class DisposeSubscriber<T> extends Subscriber<T> {
constructor(destination: Subscriber<T>, private callback: () => void) {
super(destination);
}
unsubscribe() {
super.unsubscribe();
const { callback } = this;
if (callback) {
callback();
this.callback = undefined!;
}
}
}