-
-
Save dp-singh/53f4d952650240e9179943a917af7f70 to your computer and use it in GitHub Desktop.
Location Observable using RxJava and retrolambda
This file contains hidden or 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
import android.app.Application; | |
import android.content.Context; | |
import android.location.Criteria; | |
import android.location.Location; | |
import android.location.LocationListener; | |
import android.location.LocationManager; | |
import android.os.Bundle; | |
import android.os.Looper; | |
import rx.Observable; | |
import rx.android.schedulers.AndroidSchedulers; | |
import rx.subscriptions.Subscriptions; | |
//Location and speed observable for RxJava and retrolamda | |
public class LocationCreationObservable { | |
private static final long UPDATE_INTERVALS = 0L; | |
private static final float MIN_DISTANCE_BETWEEN_UPDATE = 0f; | |
private static final LocationManager LOCATION_MANAGER = (LocationManager) Application.getSystemService(Context.LOCATION_SERVICE); | |
private static final Observable<Location> mObservableLocation = locationObservable(); | |
private static Observable<Location> locationObservable() { | |
return Observable.create((Observable.OnSubscribe<Location>) subscriber -> { | |
Criteria criteriaLocation = new Criteria(); | |
criteriaLocation.setSpeedAccuracy(Criteria.ACCURACY_HIGH); | |
//listener callback for listening location update on the basis of above defined criteria | |
final LocationListener listenerLocation = new LocationListener() { | |
@Override | |
public void onLocationChanged(Location location) { | |
subscriber.onNext(location); | |
} | |
@Override | |
public void onStatusChanged(String provider, int status, Bundle extras) { | |
} | |
@Override | |
public void onProviderEnabled(String provider) { | |
} | |
@Override | |
public void onProviderDisabled(String provider) { | |
} | |
}; | |
LOCATION_MANAGER.requestLocationUpdates(UPDATE_INTERVALS, MIN_DISTANCE_BETWEEN_UPDATE, | |
criteriaLocation, listenerLocation, Looper.getMainLooper()); | |
//add location subscription to the subscriber | |
subscriber.add(Subscriptions.create(() -> LOCATION_MANAGER.removeUpdates(listenerLocation))); | |
}).publish().refCount(); | |
} | |
/** | |
* @return UI Thread for location. | |
*/ | |
public static Observable<Location> getObservableLocation() { | |
return mObservableLocation.observeOn(AndroidSchedulers.mainThread()); | |
} | |
/** | |
* @return UI Thread Observable for speed. | |
*/ | |
public static Observable<Speed> createObservableSpeed() { | |
return mObservableLocation.map(location -> new Speed(location.getSpeed(), location.getAccuracy())).observeOn(AndroidSchedulers.mainThread()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment