Skip to content

Instantly share code, notes, and snippets.

@tomaszrykala
Last active January 27, 2018 14:16
Show Gist options
  • Save tomaszrykala/c0161b66825f39d7aa055d4b01087734 to your computer and use it in GitHub Desktop.
Save tomaszrykala/c0161b66825f39d7aa055d4b01087734 to your computer and use it in GitHub Desktop.
Timer.kt
const val MSG = 1
class Timer(private val listener: Timer.Listener) {
interface Listener {
fun onTick(tick: Double)
fun onStart()
fun onStop()
}
private val handler = CountUpHandler(this)
fun start() {
reset()
listener.onStart()
handler.sendMessage(handler.obtainMessage(MSG))
}
fun stop() {
listener.onStop()
handler.removeMessages(MSG)
}
private fun onTick(elapsedTime: Double) {
listener.onTick(elapsedTime)
}
private fun reset() {
handler.reset()
}
class CountUpHandler(private val timer: Timer) : Handler() {
private var base: Int = 0
override fun handleMessage(msg: Message) {
synchronized(this) {
base++
timer.onTick(base / 10.0)
sendMessageDelayed(obtainMessage(MSG), 100)
}
}
fun reset() {
synchronized(this) {
base = 0
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment