Is there any rule of thumb when to bundle multiple...
# compose
l
Is there any rule of thumb when to bundle multiple single states of a
ViewModel
into one state object (e.g.
data class ViewState(..)
)? In my opinion both have advantages and disadvantages. Exposing multiple states from VM keeps changes to the UI more granular but it's more cumbersome to keep track of every single state. On the other hand, exposing just one bigger state object has better maintenance because you always have to deal with just one state in your UI but in contrast when one of the fields changes, a new object is created. Imagine you have following state object:
Copy code
data class MyScreenState(
    val isLoaded: Boolean,
    val items: List<SomeType>,
    val sortedItems: List<SomeType>,
    val recommendedItems: List<SomeType>,
)
While
isLoaded
might changes quite frequently, the other fields do not and this yields to a massive unbalanced object creation. So I'm wondering if there is any rule of thumb when to use which approach?
👀 4
f
You can map states as sealed classes Sorted items should derive of your loaded items These states should be mutually exclusive, you wouldn't want any corner unturned
l
Thanks but this question is not about sorted items or map states as sealed classes. It's about when to use which approach, the state class above is just an example. It could be of 2 fields but also of 10 fields
✔️ 2
c
To be honest I have the exact same struggle. Sometimes I feel like it would be easier to create UIState objects for every screen. But It just does not feel right to update the whole screen for every little change that occurs. At the moment we are exposing multiple StateFlows from the VM and collect them and pass them down the view hierarchy as needed. But it would be nice to have official guidelines regarding this topic.
1
d
We use this approach and do not have any problems with it. If you'll delegate only individual fields to child composables, Compose will optimize and call them only if arguments change.
Copy code
fun Content(state: UIState) {
   Child1(state.isLoaded)
   Child2(state.itemList)
   Chile3(state.recommendedItems)
}
child1 will recompose its content only when
isLoaded
changes, child2 will recompose content only if
itemList
changes etc
👍 1