Need to unsubscribe Firestore/Angularfire2 subscription

Viewed 4359

I use Firestore like so.

Use case 1:

contacts$: Observable<ContactDetail[]>;

constructor(){    
} 

ionViewDidEnter() {
   this.contacts$ = this.contactProvider.getSpecificUserContacts(this.authenticationProvider.user.uid).valueChanges();
   this.contacts$.pipe(first()).subscribe(res => { },
      err => { },
      () => { }
   );
}

Use case 2:

getAllContactCategories() {
    this.categories$ = this.categoryProvider.getAllContactCategories().valueChanges();
    this.categories$.subscribe(res => {
       this.categorySortedList = res;          
    },
      err => { }
    );
}

But I have never unsubscribed it. So do I need to do that? Otherwise, will it lead to memory leaks and draining the battery usage? I know we don't need to unsubscribed angular HTTP services since it does automatically by the framework itself. So what about Firestore/Angularfire2 observables? I have never seen such a pattern with firestore books or articles or like so.

2 Answers

Yes, It's good to unsubscribe the subscribed one. You can try this...

  contactsSub: Subscription;

constructor(){
}

ionViewDidEnter() { ... }

  ionViewDidLeave{
  this.contactsSub.unsubscribe();
  }

From angularfire2 rep: https://github.com/angular/angularfire2/issues/377

By using the first() operator you are automatically unsubscribing directly after the the subscription is initially triggered. But to answer your specific question.

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.

From https://angular.io/guide/route

In general if you wish to control when to unsubscribe, you can assign the observable to a variable

const subscription = this.subscription$.valueChanges().subscribe(...);

And then call unsubscribe on the newly created variable.

subscription.unsubscribe();
Related