Exciting Update!
After successfully finding the solution, I created a handy ng2-rx-collector tool inspired by the accepted answer to simplify the process even further. It's designed to assist anyone who might encounter similar challenges in the future.
The Initial Question
Imagine having a component with two subscriptions to hot observables. These subscriptions are set up in ngOnInit
and unsubscribed in ngOnDestroy
to prevent memory leaks or 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();
}
Although I appreciate Rx, I find the process of managing subscriptions overwhelming:
- Creating a private subscription property for each subscription
- Assigning the property to a subscription (which looks messy due to the logic placement)
- Unsubscribing from each subscription on destroy
Is there a better way to handle this?
For example, in RxSwift, they utilize a DisposeBag
to streamline the process. In TypeScript, this concept could be translated as:
private let bag = DisposeBag();
...
o1.subscribe(...).addDisposableTo(bag);
This would involve only one disposal process. However, I have been unable to find a similar function for Subscription
.
I would greatly appreciate any thoughts or suggestions on improving this process.