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?
Use the unsubscribe method A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions. To prevent these memory leaks we have to unsubscribe from the subscriptions when we are done with. We do so by calling the unsubscribe method in the Observable.
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
🎩 Automagically Unsubscribe in Angular As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak. A memory leak occurs when a section of memory that is no longer being…
Subscribe
class has an add
method that adds multiple subscriptions into one and then it can be unsubscribed
at once.
subscription1 = observable.subscribe(
// next, err, complete etc
);
subscription2 = observable.subscribe(
// next, err, complete etc
);
adding multiple subscriptions
subscription1.add(subscription2);
unsubscribing all subscriptions at once.
subscription1.unsubscribe();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With