使用场景: 当某界面内容来源不同,但需同时显示出来时 eg1: 一部分数据来自本地,一部分来自网络
Observable.zip(
queryContactsFromLocation(),
queryContactsForNet(),
new Func2<List<Contacter>, List<Contacter>, List<Contacter>>() {
@Override
public List<Contacter> call(List<Contacter> contacters, List<Contacter> contacters2) {
contacters.addAll(contacters2);
return contacters;
}
}
).compose(this.<List<Contacter>>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<Contacter>>() {
@Override
public void call(List<Contacter> contacters) {
initPage(contacters);
}
});
/**
* 模拟手机本地联系人查询
*/
private Observable<List<Contacter>> queryContactsFromLocation() {
return Observable.create(new Observable.OnSubscribe<List<Contacter>>() {
@Override
public void call(Subscriber<? super List<Contacter>> subscriber) {
ArrayList<Contacter> contacters = new ArrayList<>();
contacters.add(new Contacter("location:张三"));
contacters.add(new Contacter("location:李四"));
contacters.add(new Contacter("location:王五"));
subscriber.onNext(contacters);
subscriber.onCompleted();
}
});
}
/**效果如下:
* 模拟网络联系人列表
*/
private Observable<List<Contacter>> queryContactsForNet() {
return Observable.create(new Observable.OnSubscribe<List<Contacter>>() {
@Override
public void call(Subscriber<? super List<Contacter>> subscriber) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ArrayList<Contacter> contacters = new ArrayList<>();
contacters.add(new Contacter("net:Zeus"));
contacters.add(new Contacter("net:Athena"));
contacters.add(new Contacter("net:Prometheus"));
subscriber.onNext(contacters);
subscriber.onCompleted();
}
});
}
eg2: 当然对于来源不同、类型不同的数据我们也可以使用Zip的,只需将两种Fun2的call()方法中先暂存起来,最后在订阅回调中分离使用即可,常见的应用场所比如下面这个界面。
顶部是Html组成的Web页面,底部是原生的评论页面,数据分别来自两个不同的接口,为了保证界面的完整显示,在这里我们可以使用Zip。
Observable.zip(
mArticleProtocol.getNewsDetail(params_detail),
mCommentProtocol.getCommentList(params_comm),
new Func2<ArticleDetailBean, CommentListBean, List>() {
@Override
public List call(ArticleDetailBean articleDetailBean, CommentListBean commentBean) {
List list = new ArrayList();
list.add(articleDetailBean);
list.add(commentBean);
return list;
}
})
.observeOn(AndroidSchedulers.mainThread())
.compose(this.<List>bindUntilEvent(ActivityEvent.DESTROY))
.subscribe(
new Action1<List>() {
@Override
public void call(List list) {
initPage(list);
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
mPageLayout.setPageState(PageStateLayout.STATE_ERROR);
}
}
);
源码: https://github.com/cn-ljb/rxjava_for_android