Replace ticker flow with simple coroutine

This commit is contained in:
Florian Renaud 2023-01-31 17:34:10 +01:00
parent 9a31aa3b91
commit 3f6b60c63d

View file

@ -16,14 +16,12 @@
package im.vector.lib.core.utils.timer package im.vector.lib.core.utils.timer
import im.vector.lib.core.utils.flow.tickerFlow
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.onEach
import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicLong
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
@ -40,14 +38,12 @@ class CountUpTimer(
private val elapsedTime: AtomicLong = AtomicLong(initialTime) private val elapsedTime: AtomicLong = AtomicLong(initialTime)
private fun startCounter() { private fun startCounter() {
counterJob = tickerFlow( counterJob = coroutineScope.launch {
scope = coroutineScope, while (true) {
delayMillis = intervalInMs, delay(intervalInMs - elapsedTime() % intervalInMs)
initialDelayMillis = intervalInMs - (elapsedTime() % intervalInMs) tickListener?.onTick(elapsedTime())
) }
.map { elapsedTime() } }
.onEach { tickListener?.onTick(it) }
.launchIn(coroutineScope)
} }
var tickListener: TickListener? = null var tickListener: TickListener? = null
@ -63,7 +59,8 @@ class CountUpTimer(
fun pause() { fun pause() {
tickListener?.onTick(elapsedTime()) tickListener?.onTick(elapsedTime())
coroutineScope.cancel() counterJob?.cancel()
counterJob = null
} }
fun resume() { fun resume() {
@ -74,6 +71,7 @@ class CountUpTimer(
fun stop() { fun stop() {
tickListener?.onTick(elapsedTime()) tickListener?.onTick(elapsedTime())
coroutineScope.cancel() coroutineScope.cancel()
counterJob = null
} }
fun interface TickListener { fun interface TickListener {