Skip to content

Instantly share code, notes, and snippets.

@murki
Last active February 9, 2017 12:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save murki/dd60db7e8d5188633d276594176f8cbc to your computer and use it in GitHub Desktop.
Save murki/dd60db7e8d5188633d276594176f8cbc to your computer and use it in GitHub Desktop.
Wrapping an asynchronous API that uses listeners, by using RxJava Observable.fromAsync
public Observable<SensorEvent> observeSensorChanged(final SensorManager sensorManager, final Sensor sensor, final int samplingPeriodUs) {
return Observable.fromAsync(new Action1<AsyncEmitter<SensorEvent>>() {
@Override
public void call(final AsyncEmitter<SensorEvent> sensorEventAsyncEmitter) {
final SensorEventListener sensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
sensorEventAsyncEmitter.onNext(sensorEvent);
}
@Override
public void onAccuracyChanged(Sensor originSensor, int i) {
// ignored for this example
}
};
// (1) - unregistering listener when unsubscribed
sensorEventAsyncEmitter.setCancellation(new AsyncEmitter.Cancellable() {
@Override
public void cancel() throws Exception {
sensorManager.unregisterListener(sensorListener, sensor);
}
});
sensorManager.registerListener(sensorListener, sensor, samplingPeriodUs);
}
// (4) - specifying the backpressure strategy to use
}, AsyncEmitter.BackpressureMode.BUFFER);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment