Timers
A timer can be used to run code at a regular interval. A timer does not have to relate to a visual UI element as in this example, but can be used to update or monitor the internal state of a system.
A 'timer' is created using a LaunchedEffect element which runs as a seperate process to the main program. To get the effect of a timer we use a loop with a delay, plus the code to be run each 'tick' of the timer.
Note that the loop can be an infinite one, or could be contitional, allowing the 'timer' to be stopped.
fun main() = singleWindowApplication(
title = "Timer"
) {
App()
}
@Composable
fun App() {
var status by remember { mutableStateOf("TICK") }
Text(status)
LaunchedEffect(Unit) {
while(true) {
delay(1000)
status = if (status == "TICK" ) "TOCK" else "TICK"
}
}
}