I'm exploring Compose Recomposition with an Experience composable, and I'm a bit confused about its behavior.
In the first code snippet, Experience() was not recomposed after the button click:
@Composable
fun Experience() {
println("Expericence() : Recomposition")
var j = 5
var i by remember { mutableIntStateOf(5) }
Row {
Button(
onClick = {
i++
j++
var text = "i=$i j=$j"
println(text)
}
) {
var text = "i=$i j=$j"
println("Button() : Recomposition")
Text(text)
}
}
}
However, in this second snippet, Experience() is recomposed:
@Composable
fun Experience() {
println("Expericence() : Recomposition")
var j = 5
var i by remember { mutableIntStateOf(5) }
Row {
var text = "i=$i j=$j"
Button(
onClick = {
i++
j++
println(text)
}
) {
println("Button() : Recomposition")
Text(text)
}
}
}
Can someone explain why this is happening? In my understanding, in the second code snippet, only Row and its children should be recomposed, not the entire Experience() composable.
I suggest reading the article What is “donut-hole skipping” in Jetpack Compose?. It's exactly your usecase
To answer your question, the recomposition happens because you read the
ivariable insideRow {}in your second snippet.Compose will recompose to the nearest scope. Normally, that'd be
Row, however,Rowisinline, so the nearest scope is yourExperiencecomposable