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?
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() }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With