Compose Multi-Platform Timers

Timers

TICK Timer

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"
        }
    }
}

Delaying Events

Press the button... Click! Hello World!

Delays can be added to code in Compose using a Coroutine (runs as a separate process to the main code).

For example, after the user performs an action (e.g. clicking a button), the subsequent events that occur can be delayed.

(In this example, the button is disabled during the delayed events toi prevent them being re-triggered.)

fun main() = singleWindowApplication(
    title = "Delays"
) {
    App()
}

@Composable
fun App() {
    var message by remember { mutableStateOf("Press the button...") }
    var buttonEnabled by remember { mutableStateOf(true) }

    Text(message)

    Button(
        onClick = {
            CoroutineScope(Dispatchers.Default).launch {
                buttonEnabled = false
                message = "Click!"
                delay(2.seconds)
                message = "Hello World!"
                delay(2.seconds)
                message = "Press the button..."
                buttonEnabled = true
            }
        },
        enabled = buttonEnabled
    ) {
        Text("Click Me!")
    }
}