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

时间:2017-05-20 01:49:09

标签: android rx-android rx-java2

我是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);
                }
            });
}

1 个答案:

答案 0 :(得分:3)

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

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

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