Rxjava - 当链接observables时如何取回其他类型的流(返回值)而不是当前?

时间:2017-06-19 05:14:23

标签: rx-java

我执行了一个retrofit2 observable调用,并且在完成后将其链接到另一个observable以将结果存储到db.It看起来像这样:

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

现在我的问题是我希望订阅者取回第一个observable的结果。所以我很喜欢          订阅者返回<List<CountryModel>>而不是现在回归<List<Long>>。反正有没有这样做?不确定concat是否可以提供帮助?

1 个答案:

答案 0 :(得分:4)

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

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