There will be scenarios in your future where zip()
won't be enough. For complex architecture, or just for personal preference, you could use the And/Then/When solution. This is contained in the RxJava Joins package and combines emitted items using structures such as patterns and plans.
Our loadList()
function will be modified like this:
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); intposition = mAddedApps.size() - 1; mAdapter.addApplication(position, appInfo); mRecyclerView.smoothScrollToPosition(position); } }); }
As usual, we have two emitting sequences, observableApp
, emitting our installed apps list, and tictoc
also emitting a Long
item every second. Now we link the source Observable and()
the second Observable:
JoinObservable.from(observableApp).and(tictoc);
This creates a Pattern
object. Using this Pattern
object, we can create a Plan
object: "We have two Observables that are going to emit items, then()
what?"
pattern.then(this::updateTitle);
Now, we have a Plan
object and we can decide what's going to happen when the plan occurs:
.when(plan).toObservable()
At this point, we can subscribe to the brand new Observable, as we always do.
18.216.96.94