I am new to Kotlin and have managed to modify my Java timer class so that I can implement it with two lines of code.
I wonder if there is some way to perhaps modify it and so implement it with one line of code? Thanks for any suggestions.
Two lines implementation:
fun testTimer() {
var tmr = MyTimer(1000, true)
tmr.onTimer = { doSometing() }
}
Timer class
class MyTimer {
private var running = false
private var repeatDelayMS: Int = 0
private val handler = Handler()
var onTimer:()-> Unit = {}
private val runnable = object : Runnable {
override fun run() {
if (running) {
onTimer()
if (repeatDelayMS > 0)
handler.postDelayed(this, repeatDelayMS.toLong())
else
stop()
}
}
}
constructor(repeatDelayMS: Int, runOnCreate: Boolean) {
this.repeatDelayMS = repeatDelayMS
if (runOnCreate)
start()
}
fun start() {
running = true
handler.postDelayed(runnable, repeatDelayMS.toLong())
}
fun stop() {
running = false
handler.removeCallbacks(runnable)
}
}