geolocation.watchPosition unsubscribe error


#1

Dears, I’m having problems to unsubscribe the Ionic Native Geolocation.

Here is my code:

  watch:any;

  constructor(
    private geolocation: Geolocation
  ) { }

  ionViewDidLoad() {
    this.watch = this.geolocation.watchPosition();
    this.watch.subscribe((data) => {
      console.log(data);
    }
  }

  ionViewDidLeave() {
    this.watch.unsubscribe(); // <<<<---- the error occurs here
  }

I’m getting the error ERROR TypeError: this.watch.unsubscribe is not a function, why?


#2

Hi, you only can unsubscribe() a subscription of an observable, not the observable itself:

  watch:any;
  subscription: any;

  constructor(
    private geolocation: Geolocation
  ) { }

  ionViewDidLoad() {
    this.watch = this.geolocation.watchPosition();
    this.subscription = this.watch.subscribe((data) => {
      console.log(data);
    }); // save the subscription
  }

  ionViewDidLeave() {
    this.subscription.unsubscribe(); // <<<<---- unsubscribe the subscription (not the observable!)
  }

#3

My lack of attention! :thinking:

Thank you.