Search code examples
angularfirebaseionic3google-cloud-firestoreangularfire2

Need to unsubscribe Firestore/Angularfire2 subscription


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.


Solution

  • 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