RXJava-链​​接可观察对象时如何获取其他类型的流(返回值)而不是当前流?

j2e*_*nue 4 java rx-java

我有一个Retrofit2可观察的调用我执行,并在它完成后立即链接到另一个可观察的以将结果存储到db中。它看起来像这样:

    protected Observable<List<Long>> buildUseCaseObservable() {
         return mDataRepo.fetchCountries().flatMap(new Function<List<CountryModel>, ObservableSource<List<Long>>>() {
             @Override
             public ObservableSource<List<Long>> apply(@NonNull List<CountryModel> countryModels) throws Exception {
                 return mDataRepo.storeCountries(countryModels);
             }
         });
     }
Run Code Online (Sandbox Code Playgroud)

现在我的问题是我希望订户获取第一个可观察到的结果。因此,id希望订阅者返回,<List<CountryModel>>而不是现在返回<List<Long>>。反正有这样做吗?不确定concat是否可以提供帮助?

yos*_*riz 5

实际上,是的,您可以将flatMap()variant与一起使用resultSelector,它们可以从的输入和输出中进行选择或组合flatMap(),在您的情况下,只需返回获取的国家/地区而不是ID:

protected Observable<List<CountryModel>> buildUseCaseObservable() {
    Repo mDataRepo = new Repo();
    return mDataRepo.fetchCountries()
            .flatMap(new Function<List<CountryModel>, ObservableSource<List<Long>>>() {
                @Override
                public ObservableSource<List<Long>> apply(
                        @android.support.annotation.NonNull List<CountryModel> countryModels) throws Exception {
                    return mDataRepo.storeCountries(countryModels);
                }
            }, new BiFunction<List<CountryModel>, List<Long>, List<CountryModel>>() {
                @Override
                public List<CountryModel> apply(List<CountryModel> countryModels,
                                                List<Long> longs) throws Exception {
                    return countryModels;
                }
            });
}
Run Code Online (Sandbox Code Playgroud)