Home > Blockchain >  make addListener get data on demand only in js (no keep listening)
make addListener get data on demand only in js (no keep listening)

Time:04-14

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?

CodePudding user response:

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
   }
}

CodePudding user response:

You can wrap it in a promise and wait for it to resolve like this:

myButton.addEventListener('click', async () => {
  try {
    await DeviceMotionEvent.requestPermission();
  } catch (e) {
    // Handle error
    return;
  }

  accelHandler = await new Promise((resolve) => {
    Motion.addListener('accel', event => {
      console.log('Device motion event:', event);
      resolve(event);
    });
  });
});

Simpler and shorter:

await new Promise((resolve) => Motion.addListener('accel', resolve));

Similar to how this waits for one second, then continues execution:

await new Promise((resolve) => setTimeout(resolve, 1000));
  • Related