(五)RxJava操作符:merge合并操作符




    前面已经介绍过一个数据合并的操作符Zip,还望大家不要跟Merge操作符混淆,Merge其实只是将多个Obsevables的输出序列变为一个,方便订阅者统一处理,对于订阅者来说就仿佛只订阅了一个观察者一样。
    还是直接看Demo比较清晰:
Observable.merge(
getDataFromLocation(),
getDataFromNet()
).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);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {

}
});
private Observable<List<Contacter>> getDataFromNet() {
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();

}
});
private Observable<List<Contacter>> getDataFromLocation() {
return Observable.create(new Observable.OnSubscribe<List<Contacter>>() {
@Override
public void call(Subscriber<? super List<Contacter>> subscriber) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

List<Contacter> datas = new ArrayList<>();
datas.add(new Contacter("location:" + "张三"));
datas.add(new Contacter("location:" + "李四"));
datas.add(new Contacter("location:" + "王五"));

subscriber.onNext(datas);
subscriber.onCompleted();
}
});
}
效果图:
    
相关文章
相关标签/搜索