There are many ways to handle multiple subscriptions efficiently in a component, I have 2 ways here and wanted to know which is more efficient and why??
Step 1: creating Array
private subscriptionArray: Subscription[];
Step 2: Adding subscriptions to the array
this.subscriptionArray.push(this._storeManagementHttp.createStore(newStore).subscribe(resp => {
this._toast.success('New store created');
}));
Step 3: iterating each subscription and unsubscribing
this.subscriptionArray.forEach(subs => subs.unsubscribe());
Step 1: creating a new subscription
private subscriptions = new Subscription();
Step 2: Adding subscriptions
this.subscriptions.add(this._storeManagementHttp.createStore(newStore).subscribe(resp => {
this._toast.success('New store created');
this._router.navigate(['/store-management']);
}));
Step3: Clearing subscription
this.subscriptions.unsubscribe();
🎩 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…
You need to use . map instead of . subscribe. Later is mainly used if you want the response updated to the DOM.
Unsubscribing Manually One method we can use, is to unsubscribe manually from active subscriptions when we no longer require them. RxJS provides us with a convenient method to do this. It lives on the Subscription object and is simply called . unsubscribe() .
In Angular applications, it's always recommended to unsubscribe the observables to gain benefits like: Avoids Memory Leaks. Aborting HTTP requests to avoid unwanted calls.
You can also this one, you don't need to run loop in this case
private destroy$ = new Subject();
myservice.megohd().pipe(takeUntil(destroy$)).subscribe();
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
read here (https://www.learnrxjs.io/operators/filtering/takeuntil.html)
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