简体   繁体   中英

How can I implement a timer in a portable way in Jetpack Compose?

There's applications I'd like to write where I'd like some things to occur on a schedule.

Polling a URL for updates every few minutes seems to be a fairly common use case. In this particular case, though, I'm just trying to implement a clock.

This works:

@Composable
fun App() {
    var ticks by remember { mutableStateOf(0) }

    // Not 100% happy about this unused variable either
    val timer = remember {
        Timer().apply {
            val task = object : TimerTask() {
                override fun run() {
                    ticks++
                }
            }
            scheduleAtFixedRate(task, 1000L, 1000L)
        }
    }

    MaterialTheme {
        Text(
            // A real application would format this number properly,
            // but that's a different question
            text = "$ticks"
        )
    }
}

But I had to import java.util.Timer , so it's not going to be portable.

Jetpack Compose can do animation, so it surely has its own timer somewhere , implying there should be some portable way to do this as well, but I can't seem to figure it out.

Is there a cross-platform way to get a timer for this purpose?

In Compose you can use LaunchedEffect - it's a side effect which is run on a coroutine scope, so you can use delay inside, like this:

var ticks by remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
    while(true) {
        delay(1.seconds)
        ticks++
    }
}

I just wanted to share an alternative I have experimented with in case someone else thinks of it and encounters the same issues I have. Here is the naive implementation:

@Composable
fun Countdown(targetTime: Long, content: @Composable (remainingTime: Long) -> Unit) {
    var remainingTime by remember(targetTime) {
        mutableStateOf(targetTime - System.currentTimeMillis())
    }

    content.invoke(remainingTime)

    LaunchedEffect(remainingTime) {
        delay(1_000L)
        remainingTime = targetTime - System.currentTimeMillis()
    }
}

Assuming you want a precission of up to a second, this snippet will cause the LaunchedEffect to update a second after remainingTime is updated, updating remainingTime in relation with the current time in milliseconds. This basically creates a loop. Wrapping this logic in a @Composable is good as it prevents the excessive re-composition this would cause if you embedded your LaunchedEffect in a large component tree.

This works, but there is a catch: you will eventually notice your timer is skipping seconds. This happens because there will be some extra delay between the assignment of a new value to the remainingTime variable and the re-execution of LaunchedEffect which will essentially mean there is more than a second between updates.

Here is an improved implementation of the above:

@Composable
fun Countdown(targetTime: Long, content: @Composable (remainingTime: Long) -> Unit) {
    var remainingTime by remember(targetTime) {
        mutableStateOf(targetTime - System.currentTimeMillis())
    }

    content.invoke(remainingTime)

    LaunchedEffect(remainingTime) {
        val diff = remainingTime - (targetTime - System.currentTimeMillis())
        delay(1_000L - diff)
        remainingTime = targetTime - System.currentTimeMillis()
    }
}

We simply subtract the time it took for LaunchedEffect to re-execute from the intended delay time. This will avoid your timer skipping seconds.

The extra delay should not be an issue for the implementation in the accepted answer. The only advantage of this approach I noticed is that the loop will stop running once we navigate away from the screen. In my tests, the while loop with a true condition kept running when navigating to another Activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM