What is the best strategy to unsubscribe multiple observable in angular? Just to be clear I use this approach when the application is not big and do not need solutions such as ngrx that in this case would be an overengineering.
Currently I use a subscription instance to add all subscriptions and after that when the component was destroyed i call the unsubscribe method. But also I have seen alternatives using the takeUntil from rxjs.
export class MyComponent implements OnInit, OnDestroy {
$firstObservable: Observable<number> = timer(0, 1000);
$secondObservable: Observable<number> = timer(0, 1000);
private _subscriptions = new Subscription();
constructor() { }
ngOnDestroy(): void {
this._subscriptions .unsubscribe();
}
ngOnInit(): void {
this._subscriptions .add(
this.$firstObservable.subscribe(console.log));
this._subscriptions .add(
this.$secondObservable.subscribe(console.log));
}
}
What would be the best solution?
.subscribe
β Josef KatiΔtakeUntil
is currently considered to be the best practice. β kostakeUntil
is the easiest way you can do. Btw, you can chainthis._subscriptions.add().add().add()
calls which makes it a little shorter. β martin