Yokan / rebuild
Course 1 8624561

ReadingSessionClock.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/ReadingSessionClock.kt

implementation45 lines
1package eu.friedcutlet.yokan.ui.screens23import kotlin.time.Duration4import kotlin.time.TimeMark5import kotlin.time.TimeSource67/**8 * Foreground reading time of one reader session. It starts running; [pause] and [resume] exclude9 * background intervals, [takeSeconds] hands out the time counted so far, and [finishSeconds] closes10 * the session so later calls neither count nor resume.11 */12internal class ReadingSessionClock(private val timeSource: TimeSource = TimeSource.Monotonic) {13    private var startedAt: TimeMark? = timeSource.markNow()14    private var accumulated: Duration = Duration.ZERO15    private var closed = false1617    /** Stops counting; returns false when the clock was already paused or closed. */18    fun pause(): Boolean {19        val started = startedAt ?: return false20        accumulated += started.elapsedNow()21        startedAt = null22        return true23    }2425    /** Starts counting again unless the clock is running or closed. */26    fun resume() {27        if (!closed && startedAt == null) startedAt = timeSource.markNow()28    }2930    /** Whole seconds counted since the last take; a running clock keeps running. */31    fun takeSeconds(): Int {32        val running = pause()33        val seconds = accumulated.inWholeSeconds.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()34        accumulated = Duration.ZERO35        if (running) resume()36        return seconds37    }3839    /** Takes the remaining seconds and closes the session; later calls return 0. */40    fun finishSeconds(): Int {41        pause()42        closed = true43        return takeSeconds()44    }45}46

Search chapters, reference and source filenames.