Is it bad in compose if I have a `mutableStateList...
# compose
c
Is it bad in compose if I have a
mutableStateListOf<Item>
and then just
list.clear()
and
list.addAll()
when I get a new list that's mostly the same? My use case: I am using Firestore where you can listen to a query via a Flow. So if I listen to a query of top20Books(), and I show that in my list, but one of the ratings on the books changes, my listener will get invoked again, which will cause me to throw away the old list and add the new list. But the only item that change was the top item, where the rating changed from a 4.82 to a 4.83. Or should I take a different route on this. Like should I try to do the diffing myself?
s
I’d do this logic in the VM or above and simply present the result of this logic to Compose as a StateFlow<List<Item>>
🦜 1
1
f
As Stylianos mentioned, this should be coming from the VM or another layer, you can wrap that in a flow and have distinct by or whatever your business logic is
s
State updates are only applied when you apply the snapshot iirc, so if you do
addAll
and
clear
right next to each other, it should trigger observers only once
❤️ 1
s
Even if it functions correctly due to what Andrei mentions above, I'd still not rely on this behavior and make the code much simpler to reason about by doing what I suggested above.
j
I haven’t looked at the impl but I’d be surprised if mutableStateList provides any out-of-box optimizations like only recompsing items depending on the items in the list that changed. I think that sort of optimization comes from things like the key attribute in the item DSL for lazy lists.
All of that to say that whether you do what you suggest or do this in the VM and expose a flow I don’t think it'll have implications for recomposition
I'd say unless the list is very large or updated very frequently, there probably isn’t much of a noticeable performance difference between scrapping the list and re-adding or doing a manual diff.
c
I am doing this in the VM. Thanks @shikasd glad to know that it should trigger observers once.