Ionic loop reading sensor and sending to api

Asked

Viewed 35 times

1

Hello, I need to take consecutive readings of some sensors in Ionic 3.x but I can’t let it completely block the application. tried to do so:

  async disparaLeituras(path_id) {
    while (true) {
      console.log('laço');
      try {
        var gyscope_data = await this.deviceMotion.getCurrentAcceleration();
        console.log(gyscope_data)
      } catch (e) {
        console.log(e); // 30
      }

    }
  }

however this caused the application to lock completely, beyond the acceleration sensor I check the gyroscope and the gps too, they all return Promisses, someone knows the correct way to proceed?

  • The easiest way is to use as a default template instead of using await, but maybe this does not help your use case. What you will do with this data after?

  • I send to a dps api, if I take out the Wait I will diparar several Promisses and will end up crashing tbm

  • if recursion is a solution, dps q a promisse performs a reading it fires the next

1 answer

1


In fact, making multiple requests per second can impair app and backend performance.

You can use the watchAcceleration and the operators of rxjs to limit and / or group the accelerometer data.

Some solution options are

import { bufferTime, mergeMap } from 'rxjs/operators';

(...)

this.deviceMotion.watchAcceleration().pipe(
    bufferTime(2000),
    mergeMap(groupedData => this.apiService.sendBatchData(groupedData)),
).subscribe(response => {
    // Response da api
});
  • Collect the last reading each n seconds, discarding intermediate readings (with debauchery):
import { debounceTime, mergeMap } from 'rxjs/operators';

(...)

this.deviceMotion.watchAcceleration().pipe(
    debounceTime(2000),
    mergeMap(singleData => this.apiService.sendData(singleData)),
).subscribe(response => {
    // Response da api
});

Among others. The ideal solution will depend on your use case.

  • the debauchery would be the equivalent of running a litura function and sending every n seconds?

  • I wouldn’t say it’s equivalent. It might even be similar. But using the watchAcceleration you change the program flow and instead of ask for and expect the accelerometer response to each n milliseconds, you will be notified whenever there is an update. So, you can do whatever you want with the data that came in: discard, group, etc. in a much more declarative way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.