react-native-sensors All three sensors reading

1.2k Views Asked by At

This isn't a problem, rather it is a question. Is there a way to get data from all three sensors at once (accelerometer, gyro, magnetometer) or is it just enough to set update interval for all three the same value. Like this

setUpdateIntervalForType(SensorTypes.accelerometer, 100); setUpdateIntervalForType(SensorTypes.magenetometer, 100); setUpdateIntervalForType(SensorTypes.gyroscope, 100);

const subscription = accelerometer.subscribe(({ x, y, z, timestamp }) => console.log({ x, y, z, timestamp }) );

const subscription1 = gyroscope.subscribe(({ x, y, z, timestamp }) => console.log({ x, y, z, timestamp }) );

const subscription2 = magenetometer.subscribe(({ x, y, z, timestamp }) => console.log({ x, y, z, timestamp }) );
1

There are 1 best solutions below

3
Daniel Schmidt On BEST ANSWER

Yes, these are RxJS Observables, those allow to be combined.

Let's say you would like to have a response like this:

{ 
  accelerometer: {x,y,z,timestamp}, 
  gyroscope: {x,y,z,timestamp},
  magnetometer: {x,y,z,timestamp}
}

and you would like to only emit on this observable if you have all data, not partial data.

An implementation looks like this:

import {
  combineLatest
} from "rxjs";
import {
  map
} from 'rxjs/operators';

import {
  accelerometer,
  magnetometer,
  gyroscope
} from "react-native-sensors";


const combinedStream = combineLatest(
  accelerometer,
  magnetometer,
  gyroscope
).pipe(
  map(([accelerometerValue, magnetometerValue, gyroscopeValue]) => ({
    accelerometer: accelerometerValue,
    magnetometer: magnetometerValue,
    gyroscope: gyroscopeValue
  }))
)