Issue
I am using capacitor 3 in a project and I have this code:
import { PluginListenerHandle } from '@capacitor/core';
import { Motion } from '@capacitor/motion';
let accelHandler: PluginListenerHandle;
myButton.addEventListener('click', async () => {
try {
await DeviceMotionEvent.requestPermission();
} catch (e) {
// Handle error
return;
}
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
});
});
As you can see there's a listener in this part:
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
});
This will get the event every time there's a motion.
I want to stop it listening / looping and be able to get the event data only when it's demanded by a function.
For example:
demandData() {
// code to return the Motion event data
}
How can I do this?
Solution
You can add the eventListener
when your function is called and remove it when you don't need it anymore (if I understood your needs correctly). this is written in JS
, but i believe you would be able to translate it to TS
:)
let eventData;
demandData() {
accelHandler = await Motion.addListener('accel', event => {
console.log('Device motion event:', event);
eventData = event
});
}
gotData() {
if (eventData) {
Motion.removeAllListeners('accel')
eventData = null
}
}
Answered By - Guy Nachshon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.