dewildte
03/24/2021, 4:20 PMViewModel
is it better to expose a single state object or multiple objects that make up the state?
For example let’s say I have two properties title: String
and isComplete: String
that could change over time.
The first option would be to wrap them up like so:
data class State(
val title: String = ",
val isComplete: Boolean = false
)
And then exposing it like this:
// MyViewModel.kt
val state: StateFlow<State>
And consuming it like this:
@Composable
fun ToDoUI(viewModel: MyViewModel) {
val state by viewModel.state.collectAsState()
...
}
OR is it better to decompose the state and expose it like so:
// MyViewModel.kt
val title: StateFlow<String>
val isComplete: StateFlow<Boolean>
And then consume like this:
@Composable
fun ToDoUI(viewModel: MyViewModel) {
val title by viewModel.title.collectAsState()
val isComplete by viewModel.isComplete.collectAsState()
...
}
What are the ramifications for my composables between the two?
Is there any performance issues or “gotchas” I should be aware of here?dewildte
03/24/2021, 4:23 PMjulioromano
03/24/2021, 4:24 PMdewildte
03/24/2021, 4:25 PMdewildte
03/24/2021, 4:25 PMjulioromano
03/24/2021, 4:25 PMjulioromano
03/24/2021, 4:27 PMjulioromano
03/24/2021, 4:29 PMjulioromano
03/24/2021, 4:33 PMdewildte
03/24/2021, 4:39 PMisComplete
changes in
the State
object. Only the composables that reference isComplete
will get recomposed?dewildte
03/24/2021, 4:40 PMjulioromano
03/24/2021, 4:47 PMGiven my example code, andchanges inisComplete
theMore or less yes but perhaps not in the exact way you think, check out this chat message from that thread in particular: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1611248248029100?thread_ts=1611232921.023400&cid=CJLTWPH7Sobject. Only the composables that referenceState
will get recomposed?isComplete
dewildte
03/24/2021, 4:51 PMval state by stateFlow.collectAsState()
Column {
// Scope A
Button(onClick = onClick1) {
// Scope B
Text(text = "One ${state.firstCounter}")
}
Button(onClick = onClick2) {
// Scope C
Text(text = "Two ${state.secondCounter}")
}
}
Is better then this:
val state by stateFlow.collectAsState()
Column {
// Scope A
MyButton(
text = "One ${state.firstCounter}",
onClick = onClick1
)
MyButton(
text = "Two ${state.secondCounter}",
onClick = onClick2
)
}
julioromano
03/24/2021, 4:52 PMdewildte
03/24/2021, 4:52 PMjulioromano
03/24/2021, 4:53 PMdewildte
03/24/2021, 4:55 PMjulioromano
03/24/2021, 4:55 PMdewildte
03/24/2021, 4:55 PMSean McQuillan [G]
03/24/2021, 5:22 PMSean McQuillan [G]
03/24/2021, 5:22 PMdewildte
03/24/2021, 5:29 PM