Last active
March 16, 2017 11:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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