Search code examples
android-jetpack-composeandroid-jetpackandroid-compose-textfield

How to reset remembered mutable state in composable?


I used this example from here:

@Composable
private fun TimedLayout() {
    var show by remember { mutableStateOf(true) }

    LaunchedEffect(key1 = Unit){
        delay(5000)
        show = false
    }
    Column(modifier=Modifier.fillMaxSize()) {
        Text("Box showing: $show")
        if(show){
            Box{
                Text(text = "BlaBla"    )
            }
        }
    }
}

That works in my case fine for the first time. When I immediately call TimedLayout() again after the Text() disappeared, the remembered show flag remains false and no Text is showing up.

How can I start the composable with a fresh show as true? How can I solve this otherwise?


Solution

  • The issue is within in which scope show is cached. Next recomposition on TimedLayout() will enforce new key in the compose and therefore new value.

    You need to move the state one level up or in the caller site.