sábado, 23 de julio de 2016

Pagination with RecyclerView using RxAndroid



This technique supposes that MVP is implemented, however applies even if that isn't the case.

1. Create Rx event scroll over RecycleView component.


@Bind(R.id.recycler_view)
RecyclerView mRecyclerView;

//mMainPresenter is my presenter (MVP pattern).
mMainPresenter.loadPager(RxRecyclerView.scrollEvents(mRecyclerView));

/**
* Management pagination how component Rx.
* @param observable : Observable from RecycleView component.
*/
public void loadPager(Observable observable) {
mCompositeSubscription.add(observable
        .subscribeOn(AndroidSchedulers.mainThread())
        .subscribe(recyclerViewScrollEvent -> {
            getMvpView().updateScroll();
        }));
}

//My view (MVP pattern) interface should have the update scroll operation
void updateScroll();

//My activity should implement the update scroll operation

@Override
public void updateScroll() {
    visibleItemCount = layoutManager.getChildCount();
    pastVisibleItems = layoutManager.findFirstVisibleItemPosition();
    if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
        totalItemCount = totalItemCount + Constants.OFFSET_PAGINATION;
        //Here I call the API service with the next page param.
    }
}

2. Declare the variables for pagination.

//The variables visibleItemCount, pastVisibleItems, totalItemCount and mLinearLayoutManager are defined in my activity


private int pastVisibleItems;
private int visibleItemCount;
private int totalItemCount;
private LinearLayoutManager mLinearLayoutManager;

//visibleItemCount and pastVisibleItems variables are initialized when the updateScroll() is overrided.

//totalItemCount variable is initialized when the list items is loaded.
totalItemCount = layoutManager.getItemCount();

//mLinearLayoutManager variable is initialized in onCreate method and used how layoutManager for my recycleView
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);

3. Finally, in onCreate method call the loadPager event.

mMainPresenter.loadPager(RxRecyclerView.scrollEvents(mRecyclerView));


You can see a real application on Git https://github.com/yaircarreno/QueryMovies


No hay comentarios:

Publicar un comentario