When we don't need the whole sequence but only a few elements at the beginning or end, we can use take()
or takeLast()
.
What if we only want the first three elements of an Observable sequence, emit them, and then let the Observable complete? The take()
function gets an N integer as a parameter, emits only the N first elements from the original sequence, and then it completes:
private void loadList(List<AppInfo> apps) { mRecyclerView.setVisibility(View.VISIBLE); Observable.from(apps) .take(3) .subscribe(new Observer<AppInfo>() { @Override public void onCompleted() { mSwipeRefreshLayout.setRefreshing(false); } @Override public void onError(Throwable e) { Toast.makeText(getActivity(), "Something went south!", Toast.LENGTH_SHORT).show(); mSwipeRefreshLayout.setRefreshing(false); } @Override public void onNext(AppInfo appInfo) { mAddedApps.add(appInfo); mAdapter.addApplication(mAddedApps.size() - 1, appInfo); } }); }
The next figure shows an Observable sequence emitting numbers. We will apply a take(2)
function to this sequence, and then we can create a new sequence emitting just the first and second item of the Observable source.
If we want the last N elements, we just use the takeLast()
function:
Observable.from(apps) .takeLast(3) .subscribe(…);
As trivial as it sounds, it's important to note that the takeLast()
function applies only to the sequence that completes due to its nature of working with a finite amount of emitted items.
The next figure shows how we can create a sequence emitting only the last element from a Observable source:
The next figure shows what happens when we apply take()
and takeLast()
to our installed applications list example:
3.129.210.91