androidkotlin

How to call a function after delay in Kotlin?


As the title, is there any way to call a function after delay (1 second for example) in Kotlin?


Solution

  • You can use Schedule

    inline fun Timer.schedule(
        delay: Long, 
        crossinline action: TimerTask.() -> Unit
    ): TimerTask (source)
    

    example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)

    import java.util.Timer
    import kotlin.concurrent.schedule
    
    Timer("SettingUp", false).schedule(500) { 
       doSomething()
    }