Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 747
Aleks Nine Avatar asked Jan 16 '26 23:01

Aleks Nine


1 Answers

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()
  }
}
like image 72
inteist Avatar answered Jan 19 '26 15:01

inteist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!