项目中我们往往会有这样的需求,一个页面,可能存在多个请求,并且每个请求返回的是不同的数据,当用户进入页面的时候,我们需要向服务器请求两次,当第一个请求成功之后,我们紧接着去请求第二个,并且两个请求同时成功之后,请求才真正成功,有一个请求失败,就提示用户请求失败。我们现在用到了rxjava 那么实现这个请求合并就很简单了
具体实现:
guithub项目地址https://github.com/wj576038874/mvp-rxjava-retrofit-okhttp
Observable<List<Topic>> observable1 = OkHttpUtils.getRetrofit().create(ApiService.class).loadTopicList(1);
Observable<List<New>> observable2 = OkHttpUtils.getRetrofit().create(ApiService.class).loadNewsList(1);
Observable<TopicsAndNews> observable = Observable.zip(observable1, observable2, new Func2<List<Topic>, List<New>, TopicsAndNews>() {
@Override
public TopicsAndNews call(List<Topic> topics, List<New> news) {
TopicsAndNews topicsAndNews = new TopicsAndNews();
topicsAndNews.setNews(news);
topicsAndNews.setTopics(topics);
return topicsAndNews;
}
});
Subscriber<TopicsAndNews> subscriber = new DialogSubscriber<TopicsAndNews>(dialog) {
@Override
protected void onSuccess(TopicsAndNews topicsAndNews) {
onLoadDatasListener.onSuccess(topicsAndNews);
}
@Override
protected void onFailure(String msg) {
onLoadDatasListener.onFailure(msg);
}
};
observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);