How to use rxandroid to listen gps location update
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 */
});