Skip to content

Instantly share code, notes, and snippets.

@devrath
Last active November 19, 2021 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devrath/102a47ad356c983f5c39ed0e54abd7d0 to your computer and use it in GitHub Desktop.
Save devrath/102a47ad356c983f5c39ed0e54abd7d0 to your computer and use it in GitHub Desktop.
Timer logic defined using the coroutines
class ProgressTimer(
private val player: Player,
private val positionListener: PositionListener,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
) {
companion object {
const val PROGRESS_TRACK_DURATION : Long = 1000
}
private val coroutineContext = CoroutineScope(ioDispatcher + SupervisorJob())
interface PositionListener {
fun progress(position: Long)
}
init {
startTimer()
}
private fun startTimer() {
coroutineContext.launch {
launchPeriodicAsync(PROGRESS_TRACK_DURATION) {
launch {
val result = withContext(Dispatchers.Main) {
return@withContext player.currentPosition
}
positionListener.progress(result)
}
}.join()
}
}
private fun CoroutineScope.launchPeriodicAsync(
repeatMillis: Long,
action: () -> Unit
) = this.launch {
if (repeatMillis > 0) {
while (isActive) { action()
delay(repeatMillis)
}
} else { action() }
}
fun purgeTimer() {
coroutineContext.cancel()
}
}
fun startingTimer() {
val progressTracker = ProgressTimer(it, (object : ProgressTimer.PositionListener {
override fun progress(position: Long) {
// -- > This is called on every interval
}
}), Dispatchers.IO)
}
progressTracker.purgeTimer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment