How to use rxandroid to listen to gps location update

These days I began to study reactive programming. In my application, I switched to using rxandroid for many cases that process data asynchronously. But I do not know how to apply for a receiver. Is there a way to subscribe to a user’s location change? Please give me an idea.

+5
source share
2 answers

You can create Observables or Subject using the LocationListener and when you get the callback in 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 a location.

There are also open source libraries you can use: Android-ReactiveLocation and cgeo

Also see API based on observations and subscription issues

Hope this helps!

+8
source

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 can use this snippet from the above library to subscribe to location changes, I believe this is the easiest 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 */ }); 
0
source

Source: https://habr.com/ru/post/1238687/


All Articles