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)
We can use decorator to manage subscriptions in component:
All subscriptions are added to array of subscriptions and implicitly unsubscribed when ngOnDestroy is called.