Last active
February 9, 2017 12:58
-
-
Save murki/dd60db7e8d5188633d276594176f8cbc to your computer and use it in GitHub Desktop.
Wrapping an asynchronous API that uses listeners, by using RxJava Observable.fromAsync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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