If I have timers on a UI in compose, and part of m...
# compose-desktop
s
If I have timers on a UI in compose, and part of my state I have the start date, what would be the best way to trigger a re-draw of the UI every second, so that the timers can be updated? It’d be obvious to just update the state with the actual value to display in a coroutine timer using
delay
, but I have a list of items potentially hundreds large, and it seems like there might be a better way that compose offers.
j
I use LaunchedTask(null) and tick from there
I update a local remember which contains the current time. Everyone who has a timestamp uses that to diff a relative.
s
@jw Would be great if you can share the code snippet... This is what i was using (i know composable should always return unit)
Copy code
@Composable
fun onEachSecond(): MutableState<Long> {
    val frame = remember { mutableStateOf(0L) }
    LaunchedEffect(Unit) {
       while (isActive) 
            delay(1000)
            frame.value += 1L
        }
    }
    return frame
}
z
That will drift away from the actual time eventually, since a 1000ms delay might only resume after 1000ms. I would read the actual current time every iteration instead.
👍 1
s
Thanks @jw That appears to work:
Copy code
val lastRequestSeconds: String = state.lastRequest?.let {
    val now = remember { mutableStateOf(Clock.System.now()) }
    LaunchedEffect(null) {
        while (isActive) {
            delay(1000)
            now.value = Clock.System.now()
        }
    }

    val sinceLastRequest = now.value.minus(it)
    sinceLastRequest.inSeconds.toInt().toString()
} ?: "-"
@suresh