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

3

9

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.

Forge answered 11/12, 2018 at 19:42 Comment(1)
try this #30846242Colostomy
C
19

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
        }
    });
Cutright answered 12/3, 2020 at 6:17 Comment(1)
Take your internet point sir!Eidolon
K
2

You can use an AdapterDataObserver on your recyclerview adapter, that will happen after submit finish :

adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            when {
                positionStart == 0 && itemCount != 0 -> {
                    mRecyclerView.smoothScrollToPosition(itemCount)
                }
                positionStart > 0 -> {
                    mRecyclerView.smoothScrollToPosition(adapter.itemCount)
                }
            }
        }

    })

Be careful with positionStart, item count value. There is also other callbacks.

Klinger answered 12/3, 2020 at 9:36 Comment(0)
C
0

As @Chintan Soni said, you can make use of the submitList commit callback. Otherwise, and in case you're using kotlin coroutines and want to wait for animations to end, I would suggest getting a look at the awaitSomething() pattern.

recyclerView.awaitScrollEnd() // custom suspend extension function

more by Chris Banes on : https://medium.com/androiddevelopers/suspending-over-views-19de9ebd7020

Cairns answered 15/3, 2020 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.