Search code examples
androidandroid-recyclerviewlistadapter

How to wait for ListAdapter.submitList() to execute and call RecyclerView.smoothScrollToPosition(0);


I have a RecyclerView recyclerView which is linked to a ListAdapter adapter. The 'list' gets new data from Firebase database and the 'list' gets sorted based on certain object properties. I then call adapter.submitList(list) to update the recyclerView - this works perfectly!

But, I want the recyclerView to scroll to the top of the list after the new data is added. But I see that adapter.submitList(list) runs on a separate thread. So how would I go about knowing when it is done submitting and call recyclerView.smoothScrollToPosition(0);

Let me know if I should provide more details.


Solution

  • ListAdapter has got another overloaded version of submitList() ListAdapter#submitList(@Nullable List<T> list, @Nullable final Runnable commitCallback) that takes second argument as Runnable.

    As per the documentation:

    The commit callback can be used to know when the List is committed, but note that it * may not be executed. If List B is submitted immediately after List A, and is * committed directly, the callback associated with List A will not be run.

    Usage:

        listAdapter.submitList(*your_new_list*, new Runnable() {
            @Override
            public void run() {
                // do your stuff
            }
        });