Joffrey
05/13/2020, 4:41 PMdebounce
behaviour, but I actually need to trigger the action periodically when there is no reset at all.
I have implemented it in multiple ways, one of which is the following:
private class ResettableTicker(
private val periodMillis: Long,
private val onTick: suspend () -> Unit
) {
private val resetEvents = Channel<Unit>()
@OptIn(ExperimentalCoroutinesApi::class) // for onTimeout
fun startIn(scope: CoroutineScope): Job = scope.launch {
while (isActive) {
select<Unit> {
resetEvents.onReceive { }
onTimeout(periodMillis, onTick)
}
}
}
suspend fun reset() {
resetEvents.send(Unit)
}
}
If I don’t want reset()
calls to suspend forever in case the ticker was never started, I also need to maintain some isRunning
state which complicates things even further.
Is there a simpler / better implementation?