Scroll ⇈ Pull ⇊ Bind and Paginate RecyclerView
Implementing infinite scrolling with pull to refresh can be laborious. With all the resources available for endless scroll where we’re either calling onLoadMore()
from the adapter (by tracking last position of ViewHolder
) or from an extension of RecyclerView.OnScrollListener
, the behavior could be anomalous. For instance, the page number returned by the callback onLoadMore()
may be off by some factor.
So I got inspired from EndlessRecyclerViewScrollListener
by nesquena, created a RecyclerViewScrollCallback
and found out a good way to do this by using a global variable loading
which toggles when method showProgress()
and hideProgress()
are called. I leveraged Pagination with RxJava (using Subjects) by Kaushik Gopal for pagination which uses the concept of Flowable
and PublishProcessor
.
RecyclerViewBindings entails a wrapper class RecyclerViewScrollCallback
which can be used to add Scroll to Bottom capability to your RecyclerView. You can use it exclusively or make use of DataBinding to bind it via the XML
.
1. In your BindingAdapter
:
a. Use BindingAdapter.setRecyclerViewScrollCallback()
to get the callback in the Presenter for OnScrolledListener.onScrolledToBottom(page: Int)
.
onScrolledListener.onScrolledToBottom(page: Int)
is called when the RecyclerView is scrolled to bottom with respect to thevisibleCount
.- Call
Presenter.onLoadMore(page: Int)
from theXML
.
b. Use BindingAdapter.setOnSwipeRefreshListener()
to get the callback in the Presenter for Runnable.run().
onPulledToRefresh.run()
is called when RecyclerView is pulled to refresh.- Call
Presenter.initialize()
from theXML
. - Set
resetLoadingState
to true inRecyclerViewScrollCallback
for invalidating the callback.
2. In your XML
, bind as follows:
Writing functions was never this “fun”. Thanks to Kotlin :)
Pagination with RxJava (using Subjects)
- Use
var paginator: PublishProcessor<Int> = PublishProcessor.create()
for pagination. - Invoke
paginator.onNext(currentPage)
when RecyclerView is scrolled to the bottom. This method resides insidepresenter.onLoadMore(page: Int)
. - The
currentPage
is incremented on successful attempt ofcontract.getUsersFromServer(page: Int)
. - The method
initialize()
is called when RecyclerView is pulled to refresh so thatcurrentPage
is reinitialized to 1 andpaginator
is recreated.
And that’s it! You just implemented Scroll ⇈ Pull ⇊ Bind Paginate RecyclerView in no time. If you’re using Architectural Components, you can also try the Paging Library. Please 👏🏻 if you think this is helpful. Happy coding! 😊