martinsumera
04/05/2024, 8:53 AMmartinsumera
04/05/2024, 8:56 AM@Composable
fun Main() {
val state = remember { mutableStateOf(false) }
BooleanTest(
changeValue = { state.value = it },
booleanValue = state.value,
)
}
@Composable
fun BooleanTest(
changeValue: (Boolean) -> Unit,
booleanValue: Boolean
) {
Timber.d("Value: $booleanValue")
changeValue(true)
Timber.d("Value: $booleanValue")
}
The output of this code is
Value: false
Value: false
which is quite confusing because this (but more complex) caused some bugs in our code. We changed state in our viewmodel but it wasn't propagated due this.
I would expect the output of this be
Value: false
Value: false
Value: true
Value: true
I'm thinking about this somehow incorrectly or is this intended behavior? This thing is fixed when I place changeValue
call to the SideEffect. Then it works fiine. But still, didn't expect such behavior.Stylianos Gakis
04/05/2024, 8:57 AMStylianos Gakis
04/05/2024, 8:58 AMmartinsumera
04/05/2024, 9:00 AMMatthew Feinberg
04/05/2024, 9:05 AMLaunchedEffect {}
or Button {}
or .clickable {}
or something like that will solve the problem.
(As an aside, I kind of wish that there were some way for code that mutates state directly in a composable function to be a compile error, to avoid mistakes!)martinsumera
04/05/2024, 9:18 AMZach Klippenstein (he/him) [MOD]
04/05/2024, 2:24 PMZach Klippenstein (he/him) [MOD]
04/05/2024, 2:34 PMStylianos Gakis
04/05/2024, 2:34 PMIt’s perfectly fine to mutate snapshot state from composition, we do it all the timeOkay you are shattering my world view, care to explain a bit here? Any examples where this is done I can look at?
Zach Klippenstein (he/him) [MOD]
04/05/2024, 2:37 PMStylianos Gakis
04/05/2024, 2:39 PM==
to the old one. That one makes sense and does not look scary at allStylianos Gakis
04/05/2024, 2:39 PMZach Klippenstein (he/him) [MOD]
04/05/2024, 2:41 PMZach Klippenstein (he/him) [MOD]
04/05/2024, 2:43 PMZach Klippenstein (he/him) [MOD]
04/05/2024, 2:43 PMStylianos Gakis
04/05/2024, 2:46 PMZach Klippenstein (he/him) [MOD]
04/05/2024, 3:27 PMColton Idle
04/05/2024, 6:56 PMOkay you are shattering my world view, care to explain a bit here? Any examples where this is done I can look at?hahaha. glad you asked stylianos because i was also 🤯
Composable functions are always ran in snapshots. Any snapshot state that is changed by a composable will be ignored if that composition is discarded.I think i knew that but forgot. thats a good one to remember.
Matthew Feinberg
04/05/2024, 7:37 PMchanging a state in the same composition where the state is created doesn’t trigger recomposition where it’s readAhh, this is very useful to know! And explains a lot of things.....
Zach Klippenstein (he/him) [MOD]
04/05/2024, 7:51 PM