I have basic composable as in the following:
var timer by remember { mutableStateOf(0) }
Column {
Text(text = timer.toString())
Button(onClick = { timer++ }) {
Text(text = "Add")
}
}
When button is clicked, internal state which is timer will be increased by one and since it has been used in the Text component, recomposition will be occurred. But if I have LazyColumn instead of Column as in the following:
var timer by remember { mutableStateOf(0) }
LazyColumn {
item(contentType = "timer") {
Text(text = timer.toString())
}
item {
Button(onClick = { timer++ }) {
Text(text = "Add")
}
}
}
Recomposition does not occur, Do not we expect it to be recomposed since the state has been changed?
When a State is read it triggers recomposition in nearest scope.
First example:
When the screen is displayed you can find:
When the
Button
"Add" is clicked only the item with the Text is recomposed.It happens because it recompose the scope that are reading the values that changes:
Text(text = timer.toString())
.Using a
Column
instead of aLazyColumn
:When the screen is diplayed:
When the
Button
"Add" is clicked all the composable is recomposed:Also in this case it happens because it recompose the scope that are reading the values that changes:
Text(text = timer.toString())
.The scope is a function that is not marked with inline and returns Unit. The
Column
is an inline function and it means that Column doesn't have an own recompose scopes.To log composition use this composable: