Rik van Velzen
Rik van Velzen

Reputation: 2015

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?

Upvotes: 4

Views: 2733

Answers (4)

Rik van Velzen
Rik van Velzen

Reputation: 2015

Or I like this version too:

Wrap whatever code block you want to be executed within { ... }

{ invokeSomeMethodHere() }.withDelay()

And have an extension function that invokes the Runnable after a certain delay:

fun <R> (() -> R).withDelay(delay: Long = 250L) {

    Handler().postDelayed({ this.invoke() }, delay)
}

Upvotes: 2

Sam
Sam

Reputation: 9944

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() }

Upvotes: 7

Jorn Vernee
Jorn Vernee

Reputation: 33845

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.

Upvotes: 6

Marc LaQuay
Marc LaQuay

Reputation: 199

For example, you can declare your global variables like:

private var handler: Handler = Handler()
private lateinit var runnableNewUrlBackground: Runnable

And also declare the function as global

init {
    runnableNewUrlBackground = Runnable {
        // Your function code here
        myCustomFun();
    }
}

Then, when you want to call this, just use:

handler.postDelayed(runnableNewUrlBackground, YOUR_DESIRED_TIME)

Upvotes: 0

Related Questions