ursus
10/27/2023, 4:44 PM@Composable
fun MyScreen(viewModel: MyViewModel) {
val state by viewModel.state.collectAsState()
Scaffold {
Column(
modifier = Modifier.fillMaxSize()
) {
Toolbar(
titleRes = BR.string.main_title,
onBackClick = viewModel::backClick
)
Text(state.title)
}
}
}
or
@Composable
fun MyScreen(viewModel: MyViewModel) {
Scaffold {
Column(
modifier = Modifier.fillMaxSize()
) {
val state by viewModel.state.collectAsState()
Toolbar(
titleRes = BR.string.main_title,
onBackClick = viewModel::backClick
)
Text(state.title)
}
}
}
is there any difference in terms of recomposition/performance between the two, as to where the state is collected?
I read that when state changes the nearest composable parent is found and only that is recomposed, correct?
So by that logic n.2 is superior, where it only recomposes the Column & children , right? Whereas the first one recomposes the whole screen (obviously most of it will be no-op, but still, it has to do the diffing, right?
probably the performance is negligible, but help me establish a the correct patternAlbert Chang
10/27/2023, 5:04 PMcollectAsState() converts a flow into a state, but doesn’t read the state.
That said, the general idea that putting a state higher in the hierarchy can potentially result in more recompositions is correct.ursus
10/27/2023, 5:06 PMstate.title and then look for a parent, which is the ˙Column and recompose that?Albert Chang
10/27/2023, 5:11 PMColumn will not introduce a recompose scope. Read this post for more details.ursus
10/27/2023, 5:12 PMScaffold needs to be recomposedAlbert Chang
10/27/2023, 5:18 PMursus
10/27/2023, 5:21 PMAlbert Chang
10/27/2023, 5:23 PMAlbert Chang
10/27/2023, 5:27 PMxoangon
10/28/2023, 7:06 AMcollectAsState() converts a flow into a state, but doesn’t read the state
>
val state = viewModel.state.collectAsState() you're not reading the state, but if you use by then it does, as it resolves the State<UiModel> wrapper.val state by viewModel.state.collectAsState() does read the state, so I would expect both code snippets to behave a little different in terms of recomposition:MyScreenScaffold then the closest recomposition scope is the one of ScaffoldAlbert Chang
10/28/2023, 7:18 AMval _state = viewModel.state.collectAsState()
val state
get() = _state.value
That's how property delegate works.xoangon
10/28/2023, 7:32 AM