Last active
November 19, 2021 14:47
-
-
Save devrath/102a47ad356c983f5c39ed0e54abd7d0 to your computer and use it in GitHub Desktop.
Timer logic defined using the 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 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() | |
} | |
} |
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
fun startingTimer() { | |
val progressTracker = ProgressTimer(it, (object : ProgressTimer.PositionListener { | |
override fun progress(position: Long) { | |
// -- > This is called on every interval | |
} | |
}), Dispatchers.IO) | |
} |
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
progressTracker.purgeTimer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment