In 2 occasions so far I needed some way to execute...
# coroutines
j
In 2 occasions so far I needed some way to execute an action after some time of inactivity, with a way to notify that there is activity (to prevent the timeout action from being triggered). Are there some built-in features that would allow me to achieve that? It may look like
debounce
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:
Copy code
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?