如何使用 RxAndroid 监听 GPS 位置更新

6

我最近开始学习响应式编程。在我的应用程序中,我已经开始在许多异步处理数据的情况下使用rxandroid。但是我不知道如何将其应用于位置监听器。有没有办法订阅用户位置更改?请给我一些思路。

3个回答

11

使用 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

希望这可以帮到您!


3

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

0

这是一个很好的主题,解释了如何将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))
}

}

从这个主题中,你可以查看代码在这里

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接