Last active
January 30, 2023 15:24
-
-
Save mr5z/e997cd23844b9461f84d5ceede0e4c86 to your computer and use it in GitHub Desktop.
Resumable CountdownTimer
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 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() | |
} | |
} |
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
Thank you so much for your contribution. This has saved my a lot of time.