Issue
Checking out codelab's basic tutorial there is a snippet to increase counter on button when clicked
@Composable
fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
val counterState = remember { mutableStateOf(0) }
Column(modifier = Modifier.fillMaxHeight()) {
Column(modifier = Modifier.weight(1f)) {
for (name in names) {
Greeting(name = name)
Divider(color = Color.Black)
}
}
Counter(
count = counterState.value,
updateCount = { newCount ->
counterState.value = newCount
}
)
}
}
@Composable
fun Counter(count: Int, updateCount: (Int) -> Unit) {
Button(
onClick = { updateCount(count + 1) },
colors = ButtonConstants.defaultButtonColors(
backgroundColor = if (count > 5) Color.Green else Color.White
)
) {
Text("I've been clicked $count times")
}
}
It is clear that remember { mutableStateOf(0) }
stores the state/value. My question is what remember does under the hood. Using var count = remember { 0 }
or mutableStateOf(0)
without remember does not increase the value.
fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
var count = remember { 0 }
Column(modifier = Modifier.fillMaxHeight()) {
Column(modifier = Modifier.weight(1f)) {
for (name in names) {
Greeting(name = name)
Divider(color = Color.Black)
}
}
Counter(
count = count,
updateCount = { newCount ->
count = newCount
}
)
}
}
Snippet above does not update the value printed on Text
, does remember only work with MutableState
?
Solution
remember - allows you to remember state from previous recompose invocation and just this. So if you for instance randomize color at initial run. The randomized color will going to be calculated once and reused whenever re-compose is necessary.
so ... remember = store value just in case recompose will be called.
Now the second thing is knowing when re-compose should be actually triggered. and there mutable states comes to help.
mutablestate = store the value AND in case i update value trigger recompose for all elements using this data.
Answered By - Daber
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.