Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to run a function with delay using extension function

I'm trying to figure out how to use an extension function to run any method with a delay, but can't seem to figure it out.

I am trying something like below where I have a function and I want a handler to delay the execution by a certain timeInterval:

functionX().withDelay(500)
functionY().withDelay(500)

private fun Unit.withDelay(delay: Int) {
  Handler().postDelayed( {this} , delay)}

private fun Handler.postDelayed(function: () -> Any, delay: Int) {
  this.postDelayed(function, delay)}

Anyone?

like image 684
Rik van Velzen Avatar asked Dec 07 '22 17:12

Rik van Velzen


2 Answers

Another approach would be to declare a top-level (i.e. global) function like this:

fun withDelay(delay : Long, block : () -> Unit) {
    Handler().postDelayed(Runnable(block), delay)
}

Then you can call it, from anywhere, like this:

withDelay(500) { functionX() }
like image 90
Sam Avatar answered Dec 10 '22 13:12

Sam


You should put the extension on the function type, not Unit:

fun functionX() {}
fun functionY() {}

private fun (() -> Any).withDelay(delay: Int) {
     Handler().postDelayed(this , delay)
}

Usage:

::functionX.withDelay(500)
::functionY.withDelay(500)

Here, ::functionX is a reference to the global function called functionX.

like image 27
Jorn Vernee Avatar answered Dec 10 '22 11:12

Jorn Vernee