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

How to concatenate multiple RxJava observables when the next one depends on previous one?

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

以下代码工作正常,但我想知道如何改进它。有两个 Single observables(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 的结果。