How to make a composable time limited?

Viewed 1262

I have a Composable in Jetpack Compose, lets say its a Button. I would like to make it time limited, so that after this time elapses, the Composable, here the button disappears.

Is there any easy way to realize this with Composables?

Or is this a much more complex implenentation?

1 Answers

An easy way to change the state of the view after some delay is to use LaunchedEffect - it is executed in the coroutine scope, so you can use the delay function with the desired interval and change the state value when it finishes.

var isButtonVisible by remember { mutableStateOf(true) }
if (isButtonVisible) {
    Button(onClick = {}) {
        Text("Button")
    }
}
LaunchedEffect(Unit) {
    delay(5.seconds)
    isButtonVisible = false
}

A more complex example, which will also show the reverse counter:

var isButtonVisible by remember { mutableStateOf(true) }
var secondsToDisappear by remember { mutableStateOf(5) }
if (isButtonVisible) {
    Button(onClick = {}) {
        Text("Button will disappear in $secondsToDisappear seconds")
    }
}
LaunchedEffect(Unit) {
    while (secondsToDisappear > 0) {
        delay(1.seconds)
        secondsToDisappear -= 1
    }
    isButtonVisible = false
}
Related