I am trying to detect motion using ionic2. Here is the snippet of my detectMotion.ts.
import {DeviceMotion} from 'ionic-native';
@Page({
templateUrl: 'build/pages/pedometer/pedometer.html'
})
export class Pedometer {
platform;
watch;
constructor () {
this.platform = platform;
}
startWatching() {
console.log('Starting to watch');
this.watch = DeviceMotion.watchAcceleration(this.options);
this.watch.subscribe(result => {this.detectMotion(result)});
}
stopWatching() {
console.log('Stop Watching');
// this.watch.dispose();
this.watch.unsubscribe();
// this.watch.clearWatch();
}
detectMotion(result) {
console.log('Current Readings: '+ JSON.stringify(result) );
//.....do something with the results.....
this.stopWatching(); // Stop and wait for a second before restarting
setTimeout(this.startWatching(), 1000);
}
}
StartWatching is being called on a button click in the html. I have tried all 3 options that i could research on viz. unsubscribe; dispose; clearWatch But all in vain. The exact error that i have been getting is
error ORIGINAL EXCEPTION: TypeError: Object #<Observable> has no method 'unsubscribe'
from the reference of ioni2 i learn that it returns a Observable
Any help or pointer is appreciated Thanks in advance
~Dhaval
As far as I know, you should store the subscription
returned from the subscribe
call, and call unsubscribe()
to that.
You will get something like this:
export class Pedometer {
platform;
watch;
watchSub : Subscription;
constructor () {
this.platform = platform;
}
startWatching() {
console.log('Starting to watch');
this.watch = DeviceMotion.watchAcceleration(this.options);
this.watchSub = this.watch.subscribe(result => {this.detectMotion(result)});
}
stopWatching() {
console.log('Stop Watching');
// this.watch.dispose();
this.watchSub.unsubscribe();
// this.watch.clearWatch();
}
detectMotion(result) {
console.log('Current Readings: '+ JSON.stringify(result) );
//.....do something with the results.....
this.stopWatching(); // Stop and wait for a second before restarting
setTimeout(this.startWatching(), 1000);
}
}