Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,16 @@ class WorkoutScreenViewModel @Inject constructor(
private val _idSetWithRunningStopwatch = MutableStateFlow<Long?>(null)
val idSetWithRunningStopwatch = _idSetWithRunningStopwatch.asStateFlow()

private val setStopwatchTargets = mutableMapOf<Long, Int>()

fun updateIdSetWithRunningStopwatch(setId: Long?) {
_idSetWithRunningStopwatch.update { setId }
}

private suspend fun startSetStopwatch(set: UiSet) {
val startTime = System.currentTimeMillis()
val id = set.id
val targetElapsedTime = setStopwatchTargets.getOrPut(id) { set.elapsedTime }
val initialElapsedTime = if (id in idsOfSetsWithStopwatchNotStartedAtLeastOnce.value) {
_idsOfSetsWithStopwatchNotStartedAtLeastOnce.update { set ->
set.filter { it != id }.toSet()
Expand All @@ -95,12 +98,21 @@ class WorkoutScreenViewModel @Inject constructor(
}

// The loop is infinite, but the coroutine will be stopped when its Job is canceled
// or the configured set duration is reached.
while (true) {
val currentTime = System.currentTimeMillis()
val newElapsedTime = initialElapsedTime + ((currentTime - startTime) / 1000)

updateSetTime(newElapsedTime.toInt(), set.id)

if (targetElapsedTime > 0 && newElapsedTime >= targetElapsedTime) {
if (userPreferences.restTimerSoundOn.value) {
soundPlayer.playAlert()
}
updateIdSetWithRunningStopwatch(null)
return
}

delay(1000)
Comment on lines +108 to 116

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition can be simplified as shown. Also delay now uses the modern overload with duration instead of integer.

Suggested change
if (targetElapsedTime > 0 && newElapsedTime >= targetElapsedTime) {
if (userPreferences.restTimerSoundOn.value) {
soundPlayer.playAlert()
}
updateIdSetWithRunningStopwatch(null)
return
}
delay(1000)
if (targetElapsedTime in 1..newElapsedTime) {
if (userPreferences.restTimerSoundOn.value) {
soundPlayer.playAlert()
}
updateIdSetWithRunningStopwatch(null)
return
}
delay(1000.milliseconds)

}
}
Expand Down Expand Up @@ -375,6 +387,7 @@ class WorkoutScreenViewModel @Inject constructor(
if (idSetWithRunningStopwatch.value == id) {
_idSetWithRunningStopwatch.update { null }
}
setStopwatchTargets.remove(id)

_exercises.update { currentExercises ->
currentExercises.map { exercise ->
Expand Down
Loading