Creating an Observable from a list

In this example, we are going to introduce the from() function. With this particular "create" function, we can create an Observable from a list. The Observable will emit every element in the list, and we can subscribe to react to these emitted elements.

To achieve the same result of the first example, we are going to update our adapter on every onNext() function, adding the element and notifying the insertion.

We are going to reuse the same structure as the first example. The main difference is that we are not going to retrieve the installed applications' list. The list will be provided by an external entity:

mApps = ApplicationsList.getInstance().getList();

After obtaining the list, we only need to make it reactive and populate the RecyclerView item:

private void loadList(List<AppInfo> apps) {
    mRecyclerView.setVisibility(View.VISIBLE);

    Observable.from(apps)
            .subscribe(new Observer<AppInfo>() {
                @Override
                public void onCompleted() {
                    mSwipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getActivity(), "Here is the  list!", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onError(Throwable e) {
                    Toast.makeText(getActivity(), "Something went  wrong!", Toast.LENGTH_SHORT).show();
                    mSwipeRefreshLayout.setRefreshing(false);
                }

                @Override
                public void onNext(AppInfo appInfo) {
                    mAddedApps.add(appInfo);
                    mAdapter.addApplication(mAddedApps.size() - 1,  appInfo);
                }
            });
}

As you can see, we are passing the installed apps list as a parameter to the from() function, and then we subscribe to the generated Observable. The Observer is quite similar to the Observer in the first example. One major difference is that we are stopping the spinning progress bar in the onCompleted() function because we are emitting every item singularly; the Observable in the first example was emitting the whole list, so it was safe to stop the spinning progress bar in the onNext() function.

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

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