Compose good practices promote using the copy() fu...
# compose
p
Compose good practices promote using the copy() function to copy the data which doesn't change in a state transition. Copying all references from a previous state to a next state and just changing what is needed. The question, isn't this inefficient for large state classes? Is it a bad practice to set the compose mutable state snapshot policy to neverEqualPolicy() and instead of copy, just reusing the same state instance, with the new updated data.
a
Copy is just a shallow copy, keeps references to the other fields in the old object. It’s not really that bad, it’s bad if you copy every item in a collection, or recreate the entire object every time. I think it all really depends on how many mutations you actually do
p
In that sense you are correct, most of the time it is a shallow copy. However, my problem is not the copy, or the amount of copies. My problem is the need to traverse the object graph to find and update an item. The problem I am having. I got a UI state that is basically represented by two nested list, or rather a list of list. A list of menu sections where each section contains a list of menu items. Now anytime a user mark a menu item as favorite, the viewmodel gets an event to update with the menu item that needs to update. Then comes the nightmare, traversing the 2 list to find and replace the menuItem with the updated favorite property, then trigger full screen recomposition again. We improved find() performance a bit by using a map instead of a list. But still, updating the state is not so trivial. The map has to be copied to trigger recomposition. On the other hand, updating the favorite property in the menuItem itself and just trigger recomposition sounds like a simple and efficient way, but people seem to go against such a move.
I understand the disadvantage of mutable vs immutable but I think in some exceptions mutable use is very valid
a
Why not just make the favorite status a separate hashmap of state that is part of the view model state? You can then just merge them at the composable level
Whole screen composition is not a problem with stability and efficient updates
p
That sounds good 👍, I will redesign considering this principle.
z
Mutable state is perfectly fine, as long the mutable state is stored in a snapshot state object.
👍 1
p
Even for a collection Zack? Like having a collection of 100+ mutablestate instances. Is it memory friendly?
z
It would probably be better to use one of the snapshot state collection objects (
SnapshotStateList
,
SnapshotStateMap
, I think there’s also a
SnapshotStateSet
now)
💯 1
p
I saw your article, definitely taking a look at these collections, thanks