Pagination in Kotlin

private var pageNumber = 1
var pastVisibleItems = 0
var visibleItemCount = 0
var totalItemCount = 0
var previousTotal = 0
var viewThreshold = 20
var linearLayoutManager: LinearLayoutManager? = null
var isLoading = true


binding.view.addOnScrollListener(object : RecyclerView.OnScrollListener() {

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        visibleItemCount = linearLayoutManager!!.childCount
        totalItemCount = linearLayoutManager!!.itemCount
        pastVisibleItems = linearLayoutManager!!.findFirstCompletelyVisibleItemPosition()
        if (dy > 0) { // the user scroll up

            if (isLoading) {
                if (totalItemCount > previousTotal) {
                    isLoading = false
                    previousTotal = totalItemCount
                }
            }
            if (!isLoading && totalItemCount - visibleItemCount <= pastVisibleItems + viewThreshold) {
                pageNumber++
                Log.d("TAG", "Pagination: $pageNumber")
                
                isLoading = true
            }
        }
    }
})


Sign In or Register to comment.