Dealing with multiple sources brings in a new possible scenario: receiving data from multiple Observables, processing them, and making them available as a new Observable sequence. RxJava has a specific method to accomplish this: zip()
combines the value emitted by two or more Observables, transforms them according to a specified function Func*
, and emits a new value. The following figure shows how the zip()
method processes the emitted "numbers" and "letters" and makes them available as a new item:
For our real-world example, we are going to use our installed apps list and a new dynamic Observable to make the example a bit spicy:
Observable<Long> tictoc = Observable.interval(1, TimeUnit.SECONDS);
The tictoc
Observable
variable uses the interval()
function to generate a Long
item every second: simple but effective. As stated previously, we are going to need a Func
object. It will be Func2
because we are going to pass two parameters to it:
private AppInfo updateTitle(AppInfoappInfo, Long time) { appInfo.setName(time + " " + appInfo.getName()); return appInfo; }
Now, our loadList()
function will look 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); Observable .zip(observableApp, tictoc, (AppInfoappInfo, Long time) ->updateTitle(appInfo, time)) .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 you can see, zip()
has three parameters: the two Observables and Func2
, as expected.
A closer look will reveal the observeOn()
function. It will be explained in the next chapter: let's say it is a leap of faith for now.
As a result, we have:
3.21.93.20