A handler to run a task every 5 seconds. Kotlin

I would like to run a specific code every 5 seconds. I am having problems with this using a handler. How can this be done in Kotlin? Here is what I still have. It should also be noted that the Timer_Preview variable is a handler.

My code

+4
source share
2 answers

Since you cannot reference the lambda that you are currently in, and you cannot reference the property that you define when you define the lambda that you assign to it, the best solution here is an objectexpression :

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

, var, , .

+4

Kotlin (. KT-10350), , , @zsmb13

fun StartTimer() {
    Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}

fun runnable() {
    //Code here

    // Run code again after 5 seconds
    Timer_Preview.postDelayed(Runnable { runnable() }, 5000)
}

, , , StartTimer() , , , :

private val RunnableCode = Runnable {
    //Code here

    //Run code again after 5 seconds
    StartTimer()
}
+1

Source: https://habr.com/ru/post/1682147/


All Articles