2
我試圖學習RxAndroi,所以問題就像在標題上。RxAndroid - 1來自多個觀察對象的響應
1響應從多個觀測量
我想從這個2個請求響應1。
或選項編號2我也想知道如何同步它們。
第一次完成後再做第二次請求。
示例代碼:
Observable<List<CategoriesTreeModel>> categoriesTreeObservable = ApiManager.getInstanceApi().getCategoriesTree();
Subscription treeSubscription = categoriesTreeObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<CategoriesTreeModel>>() {
@Override
public void onCompleted() {
Log.e("CATALOG", "getCategoriesTree() complete");
}
@Override
public void onError(Throwable e) {
Log.e("CATALOG", "getCategoriesTree() error");
}
@Override
public void onNext(List<CategoriesTreeModel> categoriesTreeModels) {
Log.e("CATALOG", "getCategoriesTree() next");
}
});
Observable<ResponseModel<CategoriesResponse>> categoriesObservable = ApiManager.getInstanceApi().getCategories();
Subscription subscription = categoriesObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseModel<CategoriesResponse>>() {
@Override
public void onCompleted() {
Log.e("CATALOG", "getCategories() complete");
}
@Override
public void onError(Throwable e) {
Log.e("CATALOG", "getCategories() error");
}
@Override
public void onNext(ResponseModel<CategoriesResponse> categoriesResponseResponseModel) {
Log.e("CATALOG", "getCategories() onNext");
}
});
編輯: 這是一個正確的whay?
Observable.zip(categoriesObservable, categoriesTreeObservable, new Func2<ResponseModel<CategoriesResponse>, List<CategoriesTreeModel>, Object>() {
@Override
public Object call(ResponseModel<CategoriesResponse> categoriesResponseResponseModel, List<CategoriesTreeModel> categoriesTreeModels) {
for (int i = 0; i < categoriesResponseResponseModel.getList().size(); i++){
Log.e("RESPONSE", "CATEGORIES: " + categoriesResponseResponseModel.getList().get(i).getCategory_id() + " NAME: " + categoriesResponseResponseModel.getList().get(i).getTranslations().getPl_PL().getName());
}
for (int i = 0; i < categoriesTreeModels.size(); i++){
Log.e("RESPONSE", "TREE: ID " + categoriesTreeModels.get(i).getId() + " CHILD: " + (categoriesTreeModels.get(i).getChildren().size() > 0 ? " has children " : "no child"));
}
return null;
}
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
看看拉鍊operaor http://stackoverflow.com/questions/30219877/rxjava-android-how-to-use-the-zip-operator,做這裏看看https://開頭github.com/ReactiveX/RxJava/wiki/Combining-Observables – Raghunandan
它看起來不錯,但你需要把它們結合在一起返回一個調用結果,這樣,當你訂閱你獲得的物品在onNext – Raghunandan