在將來還有一些zip()滿足不了的場景。如復(fù)雜的架構(gòu),或者是僅僅為了個人愛好,你可以使用And/Then/When解決方案。它們在RxJava的joins包下,使用Pattern和Plan作為中介,將發(fā)射的數(shù)據(jù)集合并到一起。
http://wiki.jikexueyuan.com/project/rxjava/images/chapter6_11.png" alt="" />
我們的loadList()函數(shù)將會被修改從這樣:
private void loadList(List<AppInfo> apps) {
mRecyclerView.setVisibility(View.VISIBLE);
Observable<AppInfo> observableApp = Observable.from(apps);
Observable<Long> tictoc = Observable.interval(1, TimeUnit.SECONDS);
Pattern2<AppInfo, Long> pattern = JoinObservable.from(observableApp).and(tictoc);
Plan0<AppInfo> plan = pattern.then(this::updateTitle);
JoinObservable
.when(plan)
.toObservable()
.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);
}
});
}
和通常一樣,我們有兩個發(fā)射的序列,observableApp,發(fā)射我們安裝的應(yīng)用列表數(shù)據(jù),tictoc每秒發(fā)射一個Long型整數(shù)?,F(xiàn)在我們用and()連接源Observable和第二個Observable。
JoinObservable.from(observableApp).and(tictoc);
這里創(chuàng)建一個pattern對象,使用這個對象我們可以創(chuàng)建一個Plan對象:"我們有兩個發(fā)射數(shù)據(jù)的Observables,then()是做什么的?"
pattern.then(this::updateTitle);
現(xiàn)在我們有了一個Plan對象并且當(dāng)plan發(fā)生時我們可以決定接下來發(fā)生的事情。
.when(plan).toObservable()
這時候,我們可以訂閱新的Observable,正如我們總是做的那樣。