I'm trying to implement an Android timer in Kotlin which will fire an event at a defined time interval. I dont want to use TimerTask due to its documented weaknesses (see here) and although there are potentially other ways to do it, I'd like to use a Handler/Runnable in a post-delayed loop. In Java this is possible since the Runnable can refer to itself in the initializer, however in Kotlin it seems this is not possible:
private fun startBoutiqueRefreshTimer(delayMs: Long) {
val handler = Handler()
val runnable = Runnable() {
EventManager.post(BoutiqueRefreshTimerEvent())
handler.postDelayed(runnable, delayMs)
}
handler.postDelayed(runnable, delayMs)
}
because runnable cannot be resolved in the inner postDelayed call. Kotlin apparently prevents variable references from within their own initializers.
What would be a good solution to this problem, still using the Handler/Runnable approach?