https://kotlinlang.org logo
Title
f

Florian

08/24/2021, 6:37 PM
Does the nested
launch
block around
taskDao.increaseMillisCompletedToday
(which is a database operation) look dangerous? I use this to measure time but without the nested
launch
, I think the length of the database operation itself is causing imprecision. The tick interval is every 1s.
fun startTimer() {
    timerJob?.cancel()
    timerJob = applicationScope.launch {
        val selectedTask = selectedTask.first()
        if (selectedTask != null) {
            taskDao.updateLastActiveTimestamp(selectedTask.id, System.currentTimeMillis())
            startTimerService()
            timerRunningFlow.value = true
            while (true) {
                val timeBefore = SystemClock.elapsedRealtime()
                delay(TICK_DELAY)
                val timeAfter = SystemClock.elapsedRealtime()
                val elapsedTime = timeAfter - timeBefore
                launch {
                    taskDao.increaseMillisCompletedToday(selectedTask.id, elapsedTime)
                }
            }
        }
    }
}
g

groostav

08/24/2021, 7:40 PM
Right I think you hit the nail on the head. In old java terms
Delay
works as
ScheduledExecutorService.scheduleWithFixedDelay
where Im guessing what you want is
ScheduledExecutorService.scheduleAtFixedRate
I'm not sure what the best way to do that is but I think the answer really depends on how you want to handle backpressure
f

Florian

08/24/2021, 7:58 PM
@groostav Thank you for your answer. Is there something in Java or Kotlin world that gives me a fixed delay that is not affected by the time in the device's settings?
because Timer is affected by it
n

Nick Allen

08/24/2021, 11:05 PM
If fixed delay is ok, but you just want the reported time to be accurate, then you could track the total time instead of just the delay. Something like:
val startTime = SystemClock.elapsedRealtime()
var lastReportedTime = 0
while(true) {
    delay(TICK_DELAY)
    val totalElapsedTime = SystemClock.elapsedRealtime() - startTime
    taskDao.increaseMillisCompletedToday(selectedTask.id, totalElapsedTime - lastReportedTime)
    lastReportedTime = totalElapsedTime
}
🤩 1
f

Florian

08/24/2021, 11:24 PM
@Nick Allen that's a great idea!
Thanks I'll use that