Merge其实只是将多个Obsevables的输出序列变为一个,方便订阅者统一处理,对于订阅者来说就仿佛只订阅了一个观察者一样。
例子:在同一页面上获取豆瓣电影、豆瓣电视剧、豆瓣音乐、豆瓣图书的内容列表
public void getAllList(String baseUrl,String tvTag,String musicTag,String bookTag,int count,int start){
lists = new ArrayList<List<SubjectBody>>();
Observable movieObservable = mBookModel.getMovieList(baseUrl,count,start);
Observable tvObservable = mBookModel.getTvList(baseUrl,tvTag,count,start);
Observable musicObservable = mBookModel.getMusicList(baseUrl,musicTag,count,start);
Observable bookObservable = mBookModel.getBookList(baseUrl,bookTag,count,start);
Observable.merge(movieObservable,tvObservable,musicObservable,bookObservable)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Object>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Object o) {
Log.d(TAG,o.toString());
if(o instanceof MovieEntity){
Log.d(TAG,((MovieEntity) o).getSubjects().size()+";"+((MovieEntity) o).getSubjects().toString());
//电影与电视剧返回相同的数据格式,添加到list时,两个请求会各添加两次,用contains判断不管用
movieList = ((MovieEntity) o).getSubjects();
// if(!lists.contains(movieList))
if(movieList != null && movieList.size() != 0)
lists.add(movieList);
tvList = ((MovieEntity) o).getSubjects();
// if(!lists.contains(tvList))
if(tvList != null && tvList.size() != 0)
lists.add(tvList);
Log.d(TAG,lists.size()+"list.size()");
if(lists != null && lists.size() != 0){
mBookView.showMovieList(lists.get(0));
mBookView.showTvList(lists.get(lists.size()-1));
}
}
else if(o instanceof MusicEntity){
List<Music> musicList = ((MusicEntity) o).getMusics();
if(musicList != null && musicList.size() != 0){
mBookView.showMusicList(musicList);
}
}
else if(o instanceof BookEntity){
List<Book> books = ((BookEntity) o).getBooks();
if(books != null && books.size() != 0){
mBookView.showBookListNew(books);
}
}
}
});
}