Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For the Angular router events Observable, why is there no unsubscribe()?

Tags:

angular

rxjs

In my ngOnInit method I am subscribing to the Router like this:

this.router.events.subscribe(
  event => {
    if (event instanceof NavigationEnd) this.clearMessages();
  }
);

Normally, for Observables outside of the HttpClient package I call unsubscribe in the ngOnDestroy method but when I tried that here I discovered that this.router.events does not have such a method. Am I mistaken or is there something different about this Observable? Why would unsubscribe not be implemented?

like image 549
AlanObject Avatar asked Jan 19 '18 01:01

AlanObject


People also ask

Do we need to unsubscribe router events in Angular?

Generally you do not need to unsubscribe from HTTP calls. The ActivatedRoute and its observables are insulated from the Router itself so the Angular Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

How do I unsubscribe from events on my router?

events. subscribe() if you console. log(sub) you will see it has the unsubscribe method.

Do we need to unsubscribe observable in Angular?

No need to unsubscribe from internal observables of an application scoped service since this service never get's destroyed, unless your entire application get's destroyed, there is no real reason to unsubscribe from it and there is no chance of memory leaks.

How do I unsubscribe from ngOnDestroy observable?

Last but not least step is to trigger unsubscribe$ during the ngOnDestroy . We call . next() method to trigger new value emission and . complete() to automatically unsubscribe all the observers.


2 Answers

I discovered that this.router.events does not have such a method

You call unsubscribe on subscriptions, not observables. And this.router.events is an observable, not subscription. So the following would work:

const subscription = this.router.events.subscribe(...);   
subscription.unsubscribe();
like image 186
Max Koretskyi Avatar answered Sep 20 '22 08:09

Max Koretskyi


You are right, some observables need no manual unsubscription from, observables like:

  1. Router, HTTP, HTTPClient, because these are single emission observables, although implicitly, and
  2. Explicit single emission observables (e.g., finite), like first()

Similar information can be found on this reddit site also. This also means that no need to worry about memory leaks from observables in these classes.

like image 31
mohsenmadi Avatar answered Sep 20 '22 08:09

mohsenmadi