fix(timer): make resetTimer a suspend fun to avoid race condition

This resolves a race condition which can cause the Service to quit before the resetTimer coroutine resets the app state.

Closes: #78
This commit is contained in:
Nishant Mishra
2025-10-17 10:38:28 +05:30
parent 9a7b706486
commit 991808ce03

View File

@@ -102,8 +102,10 @@ class TimerService : Service() {
Actions.RESET.toString() -> {
if (timerState.value.timerRunning) toggleTimer()
resetTimer()
stopForegroundService()
skipScope.launch {
resetTimer()
stopForegroundService()
}
}
Actions.SKIP.toString() -> skipTimer(true)
@@ -278,27 +280,25 @@ class TimerService : Service() {
}
}
private fun resetTimer() {
private suspend fun resetTimer() {
updateProgressSegments()
skipScope.launch {
saveTimeToDb()
time = timerRepository.focusTime
cycles = 0
startTime = 0L
pauseTime = 0L
pauseDuration = 0L
saveTimeToDb()
time = timerRepository.focusTime
cycles = 0
startTime = 0L
pauseTime = 0L
pauseDuration = 0L
_timerState.update { currentState ->
currentState.copy(
timerMode = TimerMode.FOCUS,
timeStr = millisecondsToStr(time),
totalTime = time,
nextTimerMode = if (timerRepository.sessionLength > 1) TimerMode.SHORT_BREAK else TimerMode.LONG_BREAK,
nextTimeStr = millisecondsToStr(if (timerRepository.sessionLength > 1) timerRepository.shortBreakTime else timerRepository.longBreakTime),
currentFocusCount = 1,
totalFocusCount = timerRepository.sessionLength
)
}
_timerState.update { currentState ->
currentState.copy(
timerMode = TimerMode.FOCUS,
timeStr = millisecondsToStr(time),
totalTime = time,
nextTimerMode = if (timerRepository.sessionLength > 1) TimerMode.SHORT_BREAK else TimerMode.LONG_BREAK,
nextTimeStr = millisecondsToStr(if (timerRepository.sessionLength > 1) timerRepository.shortBreakTime else timerRepository.longBreakTime),
currentFocusCount = 1,
totalFocusCount = timerRepository.sessionLength
)
}
}