if Kotlin's `fixedRateTimer` function appropriate ...
# getting-started
f
if Kotlin's
fixedRateTimer
function appropriate and accurate enough to create a countdown timer? And is there any problem with launching a coroutine inside the timer action block?
Copy code
fun startTimer() {
        timer?.cancel()
        applicationScope.launch {
            val selectedTask = selectedTask.first()
            if (selectedTask != null) {
                taskDao.updateLastActiveTimestamp(selectedTask.id, System.currentTimeMillis())
                startTimerService()
                timerRunningFlow.value = true
                timer = fixedRateTimer(period = TICK_DELAY) {
                    applicationScope.launch {
                        taskDao.increaseMillisCompletedToday(selectedTask.id, TICK_DELAY)
                    }
                }
            }
        }
    }
e
kotlin.concurrent.fixedRateTimer uses java.util.Timer which uses java.lang.Object.wait whose precision varies by platform. how accurate does your countdown timer need to be?
f
@ephemient It's for a stopwatch, but let's say 5 seconds difference on 30 minutes would be bearable
is that within the range?
g
Yes it's fine for a stopwatch, the precision Eph is talking about is at worst +/- 10ms.
f
Alright, thank you!
I actually had to remove timer because it went nuts when I change the date of the phone manually
do you know anything about this?
does it depend on clock time?
e
assuming you're on Android?
Timer effectively uses the realtime clock so yes, it'll behave poorly if the time is adjusted
f
good to know, thank you!
I considered CountdownTimer, but counting downwards actually makes things more complicated for me
I'm now using coroutines +
delay
+ calculating the
elapsedTime
difference to combat the imprecision of
delay
seems to work fine
122 Views