Skip to content

Instantly share code, notes, and snippets.

@roschlau
Last active March 16, 2017 11:52
Show Gist options
  • Save roschlau/9a23f56fb22f211eda6b50e1ce31e304 to your computer and use it in GitHub Desktop.
Save roschlau/9a23f56fb22f211eda6b50e1ce31e304 to your computer and use it in GitHub Desktop.
A simple repeater that will repeat an action infinitely with a set interval until it is stopped. Uses Coroutines.
class Repeater(val interval: Long,
val context: CoroutineContext = UI,
val block: () -> Unit
) {
private var updatingJob: Job? = null
private val updatingJobLock = Any()
fun start() = synchronized(updatingJobLock) {
if (updatingJob != null && updatingJob!!.isActive) {
return
}
updatingJob = launch(context) {
while (isActive) {
block()
delay(interval)
}
}
}
fun stop() {
updatingJob?.cancel()
synchronized(updatingJobLock) {
updatingJob = null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment