Does the nested `launch` block around `taskDao.inc...
# coroutines
f
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.
Copy code
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
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
@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
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:
Copy code
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
@Nick Allen that's a great idea!
Thanks I'll use that