Ionic 2 Provider Observable Unsubscribing

Viewed 1581

I am working on an Ionic application and I am having an issue as to when to unsubscribe to observable used in providers. Currently what I am doing is on a page I checking whether or not the use is authenticated before entering the page. Then if they are authenticated I return the users data from firebase. Here is the function used on the page

ionViewCanEnter() {

return new Promise((resolve, reject) => {
  this.auth.isBusiness()
    .then(user => {
      this.currentUser = user;
      resolve(true);
    })
    .catch(error => {
      console.log(error);
      this.presentToast()
      reject(false)
    });
});
}

The functions I call exist in a provider. From the provider I subscribe to my users data from firebase. I am using takeUntil to handle the unsubscription of this observable once i leave the page and call dispose on the provider. My issue is when i try to renavigate to the page i am already unsubscribed from the destroy$ variable. Should I not be unsubscribing from observables from within providers because the same provider is used among pages and not reinitialized or is there something else I need to be doing. Do I need to manually call an init function for the provider whenever I load my page?

private destroy$: Subject<any>
 public isBusiness() {
    return new Promise((resolve, reject) => {
      this.isAuthenticated()
        .then(user => {
          this.userProvider.getUser(user["uid"]).takeUntil(this.destroy$).subscribe(searchedUser => {
            if (searchedUser.userType === "business") {
              resolve(searchedUser);
            } else {
              reject("You are not a business");
            }
          })
        }).catch(err => {
          reject(err);
        });
    });
  }
  public dispose() {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }

Thank you for all the help!

1 Answers
Related