Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular better way to clear subscriptions

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??

Method 1: Using Array

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());

Method 2

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();
like image 821
Varun Sukheja Avatar asked Jun 21 '19 11:06

Varun Sukheja


People also ask

What happens if we don't unsubscribe in Angular?

🎩 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…

What to use instead of subscribe in Angular?

You need to use . map instead of . subscribe. Later is mainly used if you want the response updated to the DOM.

Does RxJS take unsubscribe?

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() .

Why should we unsubscribe in Angular?

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.


1 Answers

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)

like image 113
Nikhil Kapoor Avatar answered Nov 15 '22 04:11

Nikhil Kapoor