Search code examples
androidkotlinkotlin-android-extensionspostdelayedandroid-ktx

Run a method periodically using ktx handler extensions


UPDATE: Clarification, I am looking for an extension to run a function every 1000 ms for example, without needing to use handler.postDelayed twice.

I've recently started using the android-ktx Kotlin extensions. And I've run into the handler extensions which very neatly converts

handler.postDelayed(runnable, delayInMillis)

into

handler.postDelayed(delayInMillis = 200L) {
    // some action
}

The problem I've run into is how to convert the following code, to use the ktx extensions. Is it even possible?

handler.postDelayed(object : Runnable {
    override fun run() {
        doSomething()
        handler.postDelayed(this, 1000)
    }
}, 1000)

Solution

  • This is a part of the core.ktx package

    you need to make sure it is included in your gradle file

    implementation "androidx.core:core-ktx:1.1.0"
    

    or more relevant/recent version

    Once you do, you can convert:

    handler.postDelayed(object : Runnable {
        override fun run() {
            doSomething()
        }
    }, 1000)
    

    to

    handler.postDelayed(delayInMillis = 200L) {
        doSomething()
    }
    
    

    to run this more than once just:

    while true {
      handler.postDelayed(delayInMillis = 200L) {
          doSomething()
      }
    }