Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use rxandroid to listen gps location update

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.

like image 670
Nguyen Minh Binh Avatar asked Dec 19 '15 04:12

Nguyen Minh Binh


2 Answers

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!

like image 74
pt2121 Avatar answered Nov 05 '22 14:11

pt2121


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 */
        });
like image 36
Muhammad Naderi Avatar answered Nov 05 '22 13:11

Muhammad Naderi