gpt4 book ai didi

android - 当下一个依赖于前一个时,如何连接多个 RxJava observable?

转载 作者:行者123 更新时间:2023-11-29 16:58:00 24 4
gpt4 key购买 nike

我对 Rx 的东西 super 陌生,希望提高我的知识。

下面的代码工作正常,但我想知道如何改进它。有两个 Single observable(mSdkLocationProvider.lastKnownLocation()mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude()))。第二个 observable 取决于第一个 observable 的结果。

我知道有一些操作,例如 zip、concat、concatMap、flatMap。我读了所有这些,现在我很困惑:)

private void loadAvailableServiceTypes(final Booking booking) {

final Location[] currentLocation = new Location[1];
mSdkLocationProvider.lastKnownLocation()
.subscribe(new Consumer<Location>() {
@Override
public void accept(Location location) throws Exception {
currentLocation[0] = location;
}
}, RxUtils.onErrorDefault());

mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ServiceTypeResponse>() {
@Override
public void accept(ServiceTypeResponse serviceTypeResponse) throws Exception {
onServiceTypesReceived(serviceTypeResponse.getServiceTypeList());
}
}, new CancellationConsumer() {
@Override
public void accept(Exception e) throws Exception {
Logger.logCaughtException(TAG, e);
}
});
}

最佳答案

flatMap 通常是您在第二次操作取决于第一次操作的结果时使用的运算符。 flatMap 的工作方式类似于内联订阅者。对于上面的示例,您可以编写如下内容:

mSdkLocationProvider.lastKnownLocation()
.flatMap(currentLocation -> {
mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)

您可以使用与上面相同的订阅者,它将获得 getServiceType 的结果。

关于android - 当下一个依赖于前一个时,如何连接多个 RxJava observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44081115/

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