Issue
I understand that architecturally this is definitely not a good thing to do, but I have embedded a for loop in a composable to update state as follows:
@Composable
fun WorkScreen(name: String?) {
var text by remember {
mutableStateOf(0)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Text(text = "YOU PRESSED ME $text")
}
for (i in 1..100) {
text = i
}
}
My expectation is that when I switch to this screen the for loop should update the mutableState and hence cause a recomposition which causes the time to tick up. However, instead I just get YOU PRESSED ME 0
if I put the for loop below the Box
function, or I get YOU PRESSED ME 100
if I put it above the Box
function.
The following question: Why my composable not recomposing on changing value for MutableState of HashMap?, does seem to be quite similar, but I'm not sure how it applies here. It seems to me I am updating the text value to be i
!
Solution
You shouldn't change view state directly from the composable view builder, because compose functions will be recalled often during recomposition, so your calculation will be repeated. You should use side effects instead.
If you need to show dynamic change of the value to user, then you should use animation, as Gabriele's answer suggests.
An other option is updating the value manually. Inside LaunchedEffect
you can use suspend functions, so you can change the value with a needed delay:
LaunchedEffect(Unit) {
for (i in 1..100) {
delay(1000) // update once a second
text = i
}
}
Answered By - Philip Dukhov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.