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

博客首页


(五)RxJava操作符:merge合并操作符_第1张图片
    前面已经介绍过一个数据合并的操作符Zip,还望大家不要跟Merge操作符混淆,Merge其实只是将多个Obsevables的输出序列变为一个,方便订阅者统一处理,对于订阅者来说就仿佛只订阅了一个观察者一样。
    还是直接看Demo比较清晰:
Observable.merge(
getDataFromLocation(),
getDataFromNet()
).compose(this.>bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1>() {
@Override
public void call(List contacters) {
initPage(contacters);
}
}, new Action1() {
@Override
public void call(Throwable throwable) {

}
});
private Observable> getDataFromNet() {
return Observable.create(new Observable.OnSubscribe>() {
@Override
public void call(Subscribersuper List> subscriber) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

ArrayList 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> getDataFromLocation() {
return Observable.create(new Observable.OnSubscribe>() {
@Override
public void call(Subscribersuper List> subscriber) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

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

subscriber.onNext(datas);
subscriber.onCompleted();
}
});
}
效果图:
     (五)RxJava操作符:merge合并操作符_第2张图片
源码:  https://github.com/cn-ljb/rxjava_for_android

你可能感兴趣的:(rxjava)