Good day, I need help with implementing pagination of my recyclerview, the point is that if I scroll down and hit the end of the list, then everything works fine, but if after the first such scroll I go up to the beginning of the list, then the list will update again, although it should not, this is the behavior I need to avoid, I tried many ways to do this and none helped me, tell me what I'm missing, I will be grateful for any help in this simple matter. here is my code
binding.rvNewList.addOnScrollListener(
object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!viewModel.isSearchMode) {
if (!recyclerView.canScrollVertically(1)
&& newState == RecyclerView.SCROLL_STATE_IDLE
) {
val listSizeAfterLoading = recyclerView.layoutManager!!.itemCount
if (currentListSize != listSizeAfterLoading) {
currentListSize = listSizeAfterLoading
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
//update list
}
binding.progressBar.visibility = View.VISIBLE
} else {
binding.progressBar.visibility = View.GONE
}
}
}
}
}
)
Usually, it's a good idea to use existing tools instead of reinventing them. But since you prefer to implement it yourself, it looks like you need to know the current position in the list.
Assuming you have configured your RecyclerView
with a LinearLayoutManager
, you can try this:
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val itemPosition = layoutManager.findFirstVisibleItemPosition()
If it's 0, you know you are at the top of the list.