As I know postDelayed() have two argument runnable and duration delay. What actually does below code in kotlin:
Handler().postDelayed({ sendMessage(MSG, params.id) taskFinished(params, false) }, duration)
Here 1st is two function calling and 2nd is duration delay. Where is runnable? Does this something like lambda for kotlin? Any anyone please explain this?
The postDelayed method takes two parameters Runnable and delayMillis . It adds the Runnable to the thread's message queue to be run after the specified amount of time elapses. The Runnable will execute on the thread to which this handler is attached.
postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r that are in the message queue.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue.
The Handler::postDelay
documentation can be found here and shows that the method is defined as follows:
boolean postDelayed (Runnable r, long delayMillis)
In idiomatic Kotlin APIs, we would change the order of both parameters and have the function type (i.e. SAM Runnable
) as the last argument so that it could be passed outside the parentheses. But sometimes we just have to deal with it, let's have a look at your example:
Handler(Looper.getMainLooper()).postDelayed({ sendMessage(MSG, params.id) taskFinished(params, false) }, duration)
The first argument wrapped in curly braces is a lambda which becomes the Runnable
thanks to SAM Conversion. You could make this more obvious by extracting it to a local variable:
val r = Runnable { sendMessage(MSG, params.id) taskFinished(params, false) } Handler(Looper.getMainLooper()).postDelayed(r, duration)
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