I’m having an issue where `RecyclerView` scroll po...
# android
m
I’m having an issue where
RecyclerView
scroll position is being nondeterministically ‘forgotten’ due to the adapter being updated via the collection of a
StateFlow
(in `Fragment.onCreateView()`:
Copy code
val myAdapter = // create it
viewModel.itemsFlow.collectInViewScope(this) { items ->
    myAdapter.setItems(items)
}
recyclerView.adapter = myAdapter
As a workaround (which seems to work), I just delay setting the adapter until the first search results come in:
Copy code
viewModel.itemsFlow.collectInViewScope(this) { items ->
    myAdapter.setItems(items)
    with(recyclerView) {
        if (adapter == null) {
            adapter = myAdapter
        }
    }
}
However, this feels like a hack. What is the correct way to
collect
adapter items and update the adapter so that the scroll position is not lost (when returning from a downstream fragment)?
😶 1
j
Even though this has nothign to do with kotlin, I usually do this:
Copy code
viewModel.itemsFlow.collectInViewScope(this) { items ->
    with(recyclerView) {
        (adapter as? SomeAdapter)?.updateItems(items) ?: run {
             adapter = SomeAdapter(items)
             layoutManager = LinearLayoutManager(context)
        }
    }
}
It makes sure that the adapter gets initialized with an initial list, and after that the adapter gets updated so it can do its animations
a
m
Thanks Adam, that answers my question perfectly.
👍 1
159 Views