gpt4 book ai didi

android - 等待位置,然后用 rxjava 执行改造调用

转载 作者:行者123 更新时间:2023-11-29 15:43:32 25 4
gpt4 key购买 nike

在我的应用程序中,我需要等待用户位置然后执行改造(当收到位置时)。

我有可观察的工作

mlocationService.getLocation()
.timeout(LOCATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(location -> {
Log.d(TAG, "COORDS: " + location.getLatitude() + ", " + location.getLongitude());
}, e -> Log.e(TAG, e.getMessage()));

但现在我需要用 retrofit 调用调用第二个可观察对象,有没有比将第二个可观察对象嵌套在第一个可观察对象的 onNext() 中更好的方法?

谢谢

最佳答案

是的,您可以使用 flatmap 运算符:

mlocationService.getLocation()
.timeout(LOCATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.subscribeOn(Schedulers.newThread())
.flatmap(location -> retrofitApi.getData(location))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)

订阅现在将获得改造调用的结果

如果你需要同时返回 retrofit 结果和位置,那么你可以使用 zip 运算符:

mlocationService.getLocation()
.timeout(LOCATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.subscribeOn(Schedulers.newThread())
.flatmap(location -> Observable.zip(
retrofitApi.getData(location),
Observable.just(location),
(Func2<Response<Data>, Location, ResponseLocation>) (response, location) -> {
return new ResponseLocation(response, location)
}
))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)

其中 ResponseLocation 只是一个采用位置和改造结果的类。然后订阅将获得一个 ResponseLocation 作为它的参数。

编辑

要在调用 Retrofit 之前使用位置,只需展开 lambda:

mlocationService.getLocation()
.timeout(LOCATION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.subscribeOn(Schedulers.newThread())
.flatmap(location -> {
updateMap(location);
return retrofitApi.getData(location);
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)

关于android - 等待位置,然后用 rxjava 执行改造调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com