我是Rx的新手,希望提高我的知识。
以下代码工作正常,但我想知道如何改进它。有两个单一可观察量(mSdkLocationProvider.lastKnownLocation()
和mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
)。第二个可观察量取决于第一个可观察的结果。
我知道有一些操作,如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);
}
});
}
答案 0 :(得分:3)
flatMap通常是第二个操作取决于第一个操作时使用的操作符。 flatMap的工作方式类似于内联订阅者。对于上面的示例,您可以编写如下内容:
mSdkLocationProvider.lastKnownLocation()
.flatMap(currentLocation -> {
mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)
您可以使用上面使用的相同订阅者,它将具有getServiceType的结果。