Recycler view not scrolling to the top after adding new item at the top, as changes to the list adapter has not yet occurred

Issue

I am getting the new list with new item at the start in my live data and then using its data to update the adapter

viewModel.myLiveData.observe { this, Observer { myList -> 
        adapter.submitList(myList) 
        recyclerView.scrollToPosition(0)
}

Solution

submitList does its work on a background thread, so there will always be race conditions that delays can’t solve. Fortunately, we can use a RecyclerView.AdapterDataObserver callback to be informed when the list calculations are complete:

yourRecyclerViewAdapter.registerAdapterDataObserver(object: RecyclerView.AdapterDataObserver() {
    override fun onChanged() {
        recycler_view_list.scrollToPosition(0)
    }
    override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
        recycler_view_list.scrollToPosition(0)
    }
    override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
        recycler_view_list.scrollToPosition(0)
    }
    override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
        recycler_view_list.scrollToPosition(0)
    }
    override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
        recycler_view_list.scrollToPosition(0)
    }
    override fun onItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?) {
        recycler_view_list.scrollToPosition(0)
    }
})

viewModel.myLiveData.observe { this, Observer { myList -> 
        adapter.submitList(myList) 
}

Answered By – TheGraeme

Leave a Comment