我正在努力学习RxAndroi所以问题就像在标题上一样。
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();
答案 0 :(得分:-1)
阅读有关MVP模式的内容,以便将数据逻辑与视图逻辑分开。 最简单的解决方案&#34;完成后第二次请求完成。&#34;如下所示。这种模式不是世界上最好的,但至少它会为你提供一些你可以参考的代码。
final Observable<String> firstObservable = Observable.just("A")
.delay(5, TimeUnit.SECONDS)
.doOnNext(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG, "call: " + s);
}
});
firstObservable
.subscribe();
final Observable<String> secondObservable = firstObservable
.flatMap(new Func1<String, Observable<String>>() {
@Override
public Observable<String> call(String s) {
return Observable.just(s + "B").delay(2, TimeUnit.SECONDS); // Make some api call
}
});
secondObservable.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG, "call: " + s);
}
});