Mark
04/27/2021, 2:55 PMRecyclerView
scroll position is being nondeterministically ‘forgotten’ due to the adapter being updated via the collection of a StateFlow
(in `Fragment.onCreateView()`:
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:
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)?Joost Klitsie
04/27/2021, 3:59 PMviewModel.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 animationsAdam Powell
04/27/2021, 5:00 PMMark
04/28/2021, 3:07 AM