Skip to content

Instantly share code, notes, and snippets.

@mr5z

mr5z/CustomTimer.kt

Last active Oct 20, 2020
Embed
What would you like to do?
Resumable CountdownTimer
class CustomTimer(private val millisInFuture: Long, private val countDownInterval: Long) {
private var millisUntilFinished: Long = millisInFuture
private var timer = InternalTimer(this, millisInFuture, countDownInterval)
private var isRunning = false
var onTick: ((millisUntilFinished: Long) -> Unit)? = null
var onFinish: (() -> Unit)? = null
private class InternalTimer(
private val parent: CustomTimer,
millisInFuture: Long,
countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
var millisUntilFinished: Long = parent.millisUntilFinished
override fun onFinish() {
millisUntilFinished = 0
parent.onFinish?.invoke()
}
override fun onTick(millisUntilFinished: Long) {
this.millisUntilFinished = millisUntilFinished
parent.onTick?.invoke(millisUntilFinished)
}
}
fun pause() {
if (isRunning) {
timer.cancel()
isRunning = false
}
}
fun resume() {
if (!isRunning && timer.millisUntilFinished > 0) {
timer = InternalTimer(this, timer.millisUntilFinished, countDownInterval)
start()
}
}
fun start() {
timer.start()
isRunning = true
}
fun restart() {
timer = InternalTimer(this, millisInFuture, countDownInterval)
start()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment