在复杂的商城项目中,有这么一种情况,一个页面需要请求多个接口数据,采用普通方法同时请求,但是返回的时间都不一致,就会造成页面闪烁或者抖动,用户体验不好。
rxjava zip操作符可以完成这样的操作,多个接口请求数据,所有接口请求完后,才做页面渲染。
假如要请求两个数据,一个是轮播图相关数据,一个是系统消息列表数据,
1.写一个bean合并两个数据
2. 合并两个请求
完整代码
/**
* 首页信息 合并请求
*/
@Override
public void requestHomeMsg() {
//获取轮播图 直播 信息
CommonUtils.getInstance().showInfoProgressDialog(mContext);
Observable<BaseRespose<MainHomeMsgModel>> observable1 = httpTask.requestHomeMsg(1, UserInfoModel.getInstance().getId());
//消息
Observable<BaseRespose<List<SystemMsgModel>>> observable2 = httpTask.requestSysTemMsg(UserInfoModel.getInstance().getId());
Observable.zip(observable1, observable2, new Func2<BaseRespose<MainHomeMsgModel>, BaseRespose<List<SystemMsgModel>>, ZipMainHomeDataModel>() {
@Override
public ZipMainHomeDataModel call(BaseRespose<MainHomeMsgModel> mainHomeMsgModelBaseRespose, BaseRespose<List<SystemMsgModel>> listBaseRespose) {
return new ZipMainHomeDataModel(mainHomeMsgModelBaseRespose.data, listBaseRespose.data);
}
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ZipMainHomeDataModel>() {
@Override
public void onCompleted() {
CommonUtils.getInstance().hideInfoProgressDialog();
xRecyclerView.refreshComplete();
}
@Override
public void onError(Throwable e) {
CommonUtils.getInstance().hideInfoProgressDialog();
xRecyclerView.refreshComplete();
}
@Override
public void onNext(ZipMainHomeDataModel zipMainHomeDataModel) {
if (zipMainHomeDataModel != null) {
dealHomeMsg(zipMainHomeDataModel.mainHomeMsgModel);
// dealSysMsg(zipMainHomeDataModel.list);
notifyAdapter();
}
}
});
}
public class ZipMainHomeDataModel {
public MainHomeMsgModel mainHomeMsgModel;//轮播图等信息
public List<SystemMsgModel> list;//系统消息
public ZipMainHomeDataModel(MainHomeMsgModel mainHomeMsgModel, List<SystemMsgModel> list) {
this.mainHomeMsgModel = mainHomeMsgModel;
this.list = list;
}
}