kecaroh
05/23/2024, 3:03 PMkecaroh
05/23/2024, 3:03 PM@Composable
fun RecompositionScopeScreen() {
var text by remember {
mutableStateOf("A")
}
MyText(
text = text,
onClick = { text += "A" }
)
}
@Composable
fun MyText(text: String, onClick: () -> Unit) {
Text(modifier = Modifier.clickable { onClick() }, text = text, fontSize = 32.sp)
}
When I click the text, everything recomposes - RecompositionScopeScreen, MyText and Text. I thought only MyText would recompose - Is that because the text state is read in the MyText invocation:
MyText(
text = text,
onClick = { text += "A" }
)
? Making it recompose the RecompositonScopeScreen, because the state is read in its scope, MyText recomposes because of the parameter changes and so does Text. Or am I misunderstanding something?
If i change the code to this:
@Composable
fun RecompositionScopeScreen() {
var text by remember {
mutableStateOf("A")
}
MyText {
Text(modifier = Modifier.clickable { text += "A" }, text = text, fontSize = 32.sp)
}
}
@Composable
fun MyText(content: @Composable () -> Unit) {
content()
}
Its only Text that recomposes. I assume its because it then only recomposes the content lambda scope as the state changes. Is that correct?
Thanks!Zach Klippenstein (he/him) [MOD]
05/23/2024, 5:24 PMkecaroh
05/23/2024, 5:53 PM@Composable
fun RecompositionScopeScreen() {
var text by remember {
mutableStateOf("A")
}
MyText(
text = { text },
onClick = {
text += "A"
}
)
}
@Composable
fun MyText(text: () -> String, onClick: () -> Unit) {
Text(modifier = Modifier.clickable { onClick() }, text = text(), fontSize = 32.sp)
}
I've read the documentation but I can't still grasp why does using the lambda parameter change the behavior nonoZach Klippenstein (he/him) [MOD]
05/23/2024, 9:43 PMvalue
property is read. Capturing a state object in a lambda is effectively like passing the state object itself to MyText
. This capturing is not a state read, since it doesn’t involve calling .value
.Zach Klippenstein (he/him) [MOD]
05/23/2024, 9:44 PMMyText
as well, and that lambda is capturing the state object but not reading its value
property.kecaroh
05/24/2024, 5:50 AM