Skip to content

Instantly share code, notes, and snippets.

@mr5z
Last active January 30, 2023 15:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/e997cd23844b9461f84d5ceede0e4c86 to your computer and use it in GitHub Desktop.
Save mr5z/e997cd23844b9461f84d5ceede0e4c86 to your computer and use it in GitHub Desktop.
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()
}
}
@prashant17d97
Copy link

Thank you so much for your contribution. This has saved my a lot of time.

@meet2602
Copy link

one mistake restart is not work
my solution:

fun restart() {
        timer.cancel()
        timer = InternalTimer(this, millisInFuture, countDownInterval)
        start()
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment