RxJava的combineLatest()函數(shù)有點像zip()函數(shù)的特殊形式。正如我們已經(jīng)學(xué)習(xí)的,zip()作用于最近未打包的兩個Observables。相反,combineLatest()作用于最近發(fā)射的數(shù)據(jù)項:如果Observable1發(fā)射了A并且Observable2發(fā)射了B和C,combineLatest()將會分組處理AB和AC,如下圖所示:
http://wiki.jikexueyuan.com/project/rxjava/images/chapter6_9.png" alt="" />
combineLatest()函數(shù)接受二到九個Observable作為參數(shù),如果有需要的話或者單個Observables列表作為參數(shù)。
從之前的例子中把loadList()函數(shù)借用過來,我們可以修改一下來用于combineLatest()實現(xiàn)“真實世界”這個例子:
private void loadList(List<AppInfo> apps) {
mRecyclerView.setVisibility(View.VISIBLE);
Observable<AppInfo> appsSequence = Observable.interval(1000, TimeUnit.MILLISECONDS)
.map(position ->apps.get(position.intValue()));
Observable<Long> tictoc = Observable.interval(1500, TimeUnit.MILLISECONDS);
Observable.combineLatest(appsSequence, tictoc,
this::updateTitle)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<AppInfo>() {
@Override
public void onCompleted() {
Toast.makeText(getActivity(), "Here is the list!", Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable e) {
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(AppInfoappInfo) {
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
mAddedApps.add(appInfo);
int position = mAddedApps.size() - 1;
mAdapter.addApplication(position, appInfo);
mRecyclerView.smoothScrollToPosition(position);
}
});
}
這我們使用了兩個Observables:一個是每秒鐘從我們已安裝的應(yīng)用列表發(fā)射一個App數(shù)據(jù),第二個是每隔1.5秒發(fā)射一個Long型整數(shù)。我們將他們結(jié)合起來并執(zhí)行updateTitle()函數(shù),結(jié)果如下:
http://wiki.jikexueyuan.com/project/rxjava/images/chapter6_10.png" alt="" />
正如你看到的,由于不同的時間間隔,AppInfo對象如我們所預(yù)料的那樣有時候會重復(fù)。