export class MyComponent {
private _subscription: Subscription;
ngOnInit() {
this._subscription = myObservable
.mergeMap(something)
.subscribe(
// some extra logic here
);
const anotherSubscription = myOtherObservable
.mergeMap(somethingElse)
.subscribe(
// some extra logic here
);
this._subscription.add(anotherSubscription);
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}
export class MyComponent {
private _onDestroy = new Subject();
ngOnInit() {
myObservable
.mergeMap(something)
.takeUntil(this._onDestroy)
.subscribe(
// some extra logic here
);
myOtherObservable
.mergeMap(somethingElse)
.takeUntil(this._onDestroy)
.subscribe(
// some extra logic here
);
}
ngOnDestroy() {
this._onDestroy.next();
}
}
*Note: takeUntil
will also complete the observable before unsubscribing (thanks @GerardSans)
I would prefer:
And use async in the template. I left the subscribe in there because sometimes you need to do something in the code, but often that's not needed at all.
Aside from that, I try to combine all my observables so that I don't need multiple subscribes at all. Just one should be able to cut it. If it doesn't I might need to take a look at my abstractions and add some more service/components.