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:
- Create a private subscription property for each subscription
- Assign this property to a subscription (this looks really ugly because the real logic goes to the right side)
- Unsubscribe from each subscription on destroy
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.
ngOnDestroyyou canunsubscribefrom the elements of the array. - eko