Update
After the solution was found I wrote a small helper ng2-rx-collector based on the accepted answer to make it even easier to use. Hope it helps somebody facing the same problems again and again.
Original question
Assume we have a component with two subscriptions on hot observables. We subscribe to them in ngOnInit
and unsubscribe in ngOnDestroy
in order to avoid the memory leaks / unexpected behavior:
public ngOnInit() {
this.s1 = o1.subscribe(console.debug.bind(console));
this.s2 = o2.subscribe(console.debug.bind(console));
}
public ngOnDestroy() {
this.s1.unsubscribe();
this.s2.unsubscribe();
}
I love Rx, but I literally want to kill myself every time I need to follow this:
Is there any way to improve this?
E.g. in RxSwift they have a DisposeBag
in order to improve the process, translated to typescript would be:
private let bag = DisposeBag();
...
o1.subscribe(...).addDisposableTo(bag);
And then only destroying it only once. Problem is that I cannot find any similar Subscription
function.
Any ideas / hints would be warmly welcomed.
You can do this:
private teardown$ = new Subject<void>();
public ngOnInit() {
o1.takeUntil(this.teardown$).subscribe(console.debug.bind(console));
o2.takeUntil(this.teardown$).subscribe(console.debug.bind(console));
}
public ngOnDestroy() {
this.teardown$.next();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With