Search code examples
androidkotlinhandlerrunnable

Handler to run task every 5 seconds Kotlin


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


Solution

  • 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.