Do I have to unsubscribe from ActivatedRoute (e.g. params) observables?

AngularTypescriptAngular2 Router3Angular2 Router

Angular Problem Overview


I find many examples where ActivatedRoute Observables like params or url are subscribed but not unsubscribed.

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params
    // (+) converts string 'id' to a number
    .switchMap((params: Params) => this.service.getHero(+params['id']))
    .subscribe((hero: Hero) => this.hero = hero);
}
  • Are the route objects and subscriptions destroyed automagically and newly created for every component creation?
  • Do I have to care about unsubscribing from those Observables?
  • If not, can you explain what happens with the tree of ActivatedRoute objects in Router.routerState?

Angular Solutions


Solution 1 - Angular

No

From the docs :

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.

There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Feel free to unsubscribe anyway. It is harmless and never a bad practice.

Solution 2 - Angular

As the winning answer quotes about the subscriptions to ActivatedRoute, Angular unsubscribes automatically.

> The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

In case you want to know how to unsubscribe from Observables:

import { Component, 
         OnInit,
         OnDestroy }      from '@angular/core';
import { ActivatedRoute } from '@angular/router'; 
// Type
import { Subscription } from 'rxjs/Subscription';


@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit, OnDestroy {
  paramsSubscription : Subscription;

  constructor(private activatedRoute : ActivatedRoute) { }

  /* Angular lifecycle hooks
  */
  ngOnInit() {
    console.log("Component initialized");
    this.paramsSubscription = this.activatedRoute.params.subscribe( params => {
      
    });
  }
  
  ngOnDestroy() {
    console.log("Component will be destroyed");
    this.paramsSubscription.unsubscribe();
  }

}

Solution 3 - Angular

The component will be destroyed and the routerState will become unreferenced when the router navigates to a different route, which will make them free to get garbage collected including the observable.

If you pass around references to this component to other components or services, the component won't be garbage collected and the subscription would be kept active, but I'm sure (without verifying) that the observable will be completed by the router when navigating away and cause the subscription to cancel.

Solution 4 - Angular

Whenever you are adding subscribe to a component, you always almost need to unsubscribe when the component is getting destroyed. But subscribe to the Activated route params doesn't require to unsubscribe as the router destroys the subscribe whenever its no longer needed.

Solution 5 - Angular

Http observables calls and router observables dont need to unsubscribe manually. In case you handle other kind of observbable or your own observable you should do it on ngOnDestroy(). You do it calling unsubscribe() method inside Suscription object where you storage your observable in the component.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhgoeblView Question on Stackoverflow
Solution 1 - AngularMiladView Answer on Stackoverflow
Solution 2 - AngularMarian07View Answer on Stackoverflow
Solution 3 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 4 - AngularthegautamnayakView Answer on Stackoverflow
Solution 5 - AngularYair AbadView Answer on Stackoverflow