I started learning reactive programming these days. In my application, I have turned to use rxandroid for many cases that process data asynchronously. But I don't know how to apply to location listener. Is there any way to subscribe the user location change? Please give me an idea.
You can create Observables or Subject by using LocationListener
and when getting callback in the onLocationChanged
, just call onNext with the location object.
public final class LocationProvider implements onLocationChanged {
private final PublishSubject<Location> latestLocation = PublishSubject.create();
//...
@Override
public void onLocationChanged(Location location) {
latestLocation.onNext(location);
}
}
Then you can subscribe to it in a class that needs location.
There are also some open source libraries that you could use: Android-ReactiveLocation and cgeo
Also, see Observable-based API and unsubscribe issue
Hope this helps!
How about using this awesome library ? https://github.com/patloew/RxLocation
add this to build.gradle
compile 'com.patloew.rxlocation:rxlocation:1.0.4'
you may use this snippet from the above mentioned library to subscribe on location changes, I believe this is the simplest way
// Create one instance and share it
RxLocation rxLocation = new RxLocation(context);
LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000);
rxLocation.location().updates(locationRequest)
.flatMap(location -> rxLocation.geocoding().fromLocation(location).toObservable())
.subscribe(address -> {
/* do something */
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With