combineLatest

RxJava's combineLatest() acts like a particular type of zip(). As we already learned, zip() works on the latest unzipped item of the two Observables. Instead, combineLatest() works on the latest emitted items: if Observable1 emits A and Observable2 emits B and C, combineLatest() will process AB and AC pairs, as shown in the following figure:

combineLatest

The combineLatest() function takes up to nine Observables as parameters, or even a list of Observables, if needed.

Borrowing the loadList() function from the previous example, we can modify it to achieve a real-world example for combineLatest():

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);
intposition = mAddedApps.size() - 1;
mAdapter.addApplication(position, appInfo);
mRecyclerView.smoothScrollToPosition(position);
                }
            });
}

We are using two Observables here: one emits an app from our installed apps list every second, and the second one emits a Long item every 1.5 seconds. We combine them and apply the updateTitle() function. As result, we obtain:

combineLatest

As you can see, due to the different time intervals, the AppInfo object sometimes repeats, as expected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.106