ListAdapter submitList() - How to scroll to beginning

I have an issue with my RecyclerView and ListAdapter.

Through an API, I receive items in a ascending order from older to newer.

My list is then being refreshed by calling the submitList(items) method.

However, since everything is asynchronous, after receiving the first item, the RecyclerView remains on the position of the first item received and showed. Since in the ListAdapter class there is no callback when the submitList() method completed, I cannot find a way to scroll after the updates to one of the new items that has been added.

Is there a way to intercept when ListAdapter has been updated ?


Not specific to ListAdapter, but it should work nonetheless:

Just use adapter.registerAdapterDataObserver(RecyclerView.AdapterDataObserver) and override the relevant onItemXXX method to tell your RecyclerView to scroll to whatever position.

As an example:

    adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            (recycler_view.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(positionStart, 0)
        }
    })

Kotlin : Very simple method to do this.

listAdapter.submitList(yourNewList) { 
    yourRecyclerView.scrollToPosition(0) 
}

The method to override is called:

public void onCurrentListChanged(List<T> previousList, List<T> currentList)

As the documentation reads:

Called when the current List is updated.


The inline documentation of the ListAdapter reads:

This class is a convenience wrapper around AsyncListDiffer that implements Adapter common default behavior for item access and counting.

And later on it reads:

Advanced users that wish for more control over adapter behavior, or to provide a specific base class should refer to AsyncListDiffer, which provides custom mapping from diff events to adapter positions.

This means, you'd need to extend the regular RecyclerView.Adapter, combined with a custom implementation of the AsyncListDiffer; and not the ListAdapter (which is just a convenience wrapper, with the stated basic functionality).

One can use the ListAdapter class as a template for that (not extending it is the clue), but the resulting class can then be extended and reused. else there is no chance to get control over the desired callback.