CountUpTimer.elapsedTime now returns updated value

This commit is contained in:
Florian Renaud 2023-01-30 14:25:02 +01:00
parent 7bb7a627c4
commit ecc0cb5f0b
1 changed files with 9 additions and 9 deletions

View File

@ -44,7 +44,7 @@ class CountUpTimer(initialTime: Long = 0L, private val intervalInMs: Long = 1_00
private fun startCounter() { private fun startCounter() {
tickerFlow(coroutineScope, intervalInMs) tickerFlow(coroutineScope, intervalInMs)
.filter { resumed.get() } .filter { resumed.get() }
.map { addAndGetElapsedTime() } .map { elapsedTime() }
.onEach { tickListener?.onTick(it) } .onEach { tickListener?.onTick(it) }
.launchIn(coroutineScope) .launchIn(coroutineScope)
} }
@ -52,11 +52,16 @@ class CountUpTimer(initialTime: Long = 0L, private val intervalInMs: Long = 1_00
var tickListener: TickListener? = null var tickListener: TickListener? = null
fun elapsedTime(): Long { fun elapsedTime(): Long {
return elapsedTime.get() return if (resumed.get()) {
val now = clock.epochMillis()
elapsedTime.addAndGet(now - lastTime.getAndSet(now))
} else {
elapsedTime.get()
}
} }
fun pause() { fun pause() {
tickListener?.onTick(addAndGetElapsedTime()) tickListener?.onTick(elapsedTime())
resumed.set(false) resumed.set(false)
} }
@ -66,15 +71,10 @@ class CountUpTimer(initialTime: Long = 0L, private val intervalInMs: Long = 1_00
} }
fun stop() { fun stop() {
tickListener?.onTick(addAndGetElapsedTime()) tickListener?.onTick(elapsedTime())
coroutineScope.cancel() coroutineScope.cancel()
} }
private fun addAndGetElapsedTime(): Long {
val now = clock.epochMillis()
return elapsedTime.addAndGet(now - lastTime.getAndSet(now))
}
fun interface TickListener { fun interface TickListener {
fun onTick(milliseconds: Long) fun onTick(milliseconds: Long)
} }