Auto unsubscribe in Angular

As far as we know, a component won’t be removed along with any subscriptions that have been generated in it.

When utilising observables in RxJS and wishing to subscribe to them, it is also important to keep in mind that unsubscribing will prevent memory leaks and that aborting HTTP requests will stop unnecessary calls.

So that you won’t have to think about it any longer, I have a solution for you.

We can cancel our memberships using a variety of methods.

The first one involves creating an array, pushing your subscriptions there, and then unsubscribing them all in the ngOnDestroy() lifecycle function. An illustration would be:

@Component(...)
export class AppComponent implements OnInit, OnDestroy {
  subscriptions: Subscription[] = [];

  ngOnInit(): void {
    this.subscriptions.push(of('example value').subscribe());
  }

  ngOnDestroy(): void {
    this.subscriptions.forEach((subscription: Subscription) =>
      subscription.unsubscribe()
    );
  }
}

The second method, which is fairly similar, is creating a variable of type Subscription and populating it with subscribers. In my opinion, this technique is superior to the one before since you simply need to use the unsubscribe() function to cancel all newly added subscribers; you don’t need to use a loop and unsubscribe for each one. This is how it’ll appear :

@Component(...)
export class AppComponent implements OnInit, OnDestroy {
  subscription: Subscription = new Subscription();

  ngOnInit(): void {
    this.subscription.add(of('example value').subscribe());
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

The final example, which is also my favourite, involves using variables of the type Subject<void> . No subscriptions should be added or pushed here. Instead of this, we are utilising the RxJS library’s takeUntil() operator, but we also need to remember to delete our subscribers in ngOnDestroy ().

See the code below for this solution.

@Component(...)
export class AppComponent implements OnInit, OnDestroy {
  destroy$: Subject<void> = new Subject<void>();

  ngOnInit(): void {
    of('example value').pipe(takeUntil(this.destroy$)).subscribe();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories