2015-12-19 20 views

回答

8

您可以使用LocationListener創建Observables或Subject,並且在onLocationChanged中獲取回調時,只需使用位置對象調用onNext即可。

public final class LocationProvider implements onLocationChanged { 
    private final PublishSubject<Location> latestLocation = PublishSubject.create(); 
    //... 
    @Override 
    public void onLocationChanged(Location location) { 
     latestLocation.onNext(location); 
    } 
} 

然後你可以在需要位置的類中訂閱它。

也有一些開源庫,你可以使用:Android-ReactiveLocationcgeo

而且,看到Observable-based API and unsubscribe issue

希望這有助於!

0

如何使用這個真棒圖書館? https://github.com/patloew/RxLocation

它添加到build.gradle

compile 'com.patloew.rxlocation:rxlocation:1.0.4' 

您可以使用此代碼段從上面提到的圖書館訂閱的位置變化,我相信這是最簡單的方法

// 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 */ 
     });