![](/img/trans.png)
[英]In RxJava, how to pass a variable along when chaining observables?
[英]Rxjava - when chaining observables how to get back other type of stream(return value) instead of current?
我執行了一個 retrofit2 observable 調用,並在它完成后立即鏈接到另一個 observable 以將結果存儲到 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);
}
});
}
現在我的問題是我希望訂閱者取回第一個 observable 的結果。 所以 id 喜歡訂閱者取回<List<CountryModel>>
而不是它現在取回的<List<Long>>
。 有沒有辦法做到這一點? 不確定 concat 是否可以提供幫助?
實際上,是的,您可以將flatMap()
變體與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;
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.