Handler to run task every 5 seconds Kotlin

Ryan Dailey picture Ryan Dailey · Jul 24, 2017 · Viewed 15.4k times · Source

I would like to run a certain code every 5 seconds. I am having trouble achieving this with a handler. How can this be done in Kotlin? Here is what I have so far. Also to note, the variable Timer_Preview is a Handler.

My Code

Answer

zsmb13 picture zsmb13 · Jul 24, 2017

Since you can't reference a lambda you're currently in, and you can't reference the property you're defining while you're defining the lambda you're assigning to it, the best solution here is an object expression:

val runnableCode = object: Runnable {
    override fun run() {
        handler.postDelayed(this, 5000)
    }
}

Assuming that this property is not a var because you actually want to change it while this self-calling is happening.