如何使用rxandroid监听gps位置更新

How to use rxandroid to listen gps location update

这几天开始学习响应式编程。在我的应用中,对于很多异步处理数据的情况,我转而使用rxandroid。但是我不知道如何应用到位置侦听器。有什么方法可以订阅用户位置更改吗?请给我一个主意。

您可以使用 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);
    }
}

然后您可以在需要位置的 class 中订阅它。

您还可以使用一些开源库:Android-ReactiveLocation and cgeo

另外,参见 Observable-based API and unsubscribe issue

希望对您有所帮助!

使用这个很棒的库怎么样? 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 */
        });

这是一个很好的主题,解释了如何将 LocationManager 回调 API 转换为 rxjava 流 https://medium.com/@mikenguyenvan/it-is-2020-i-still-write-a-topic-about-converting-android-callback-api-to-rxjava-stream-976874ebc4f0

总之还是用Observable.create()

比较好
private fun createLocationObservable(attributes: RxLocationAttributes): Observable<Location> {
return Observable.create { emitter ->
    val listener = getLocationListener(emitter)
    val completeListener = getOnCompleteListener(emitter)
    try {
        fusedLocationProviderClient.lastLocation.addOnSuccessListener {
            if (!emitter.isDisposed && it != null) emitter.onNext(it)
        }
        val task = fusedLocationProviderClient.requestLocationUpdates(
            getLocationRequest(attributes),
            listener,
            if (attributes.useCalledThreadToEmitValue) null else Looper.getMainLooper()
        )
        task.addOnCompleteListener(completeListener)
    } catch (e: Exception) {
        emitter.tryOnError(e)
    }
    emitter.setCancellable(getCancellable(listener))
}

}

从题目中可以看代码here