Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the postDelayed() uses in kotlin

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?

like image 388
0xAliHn Avatar asked Mar 28 '18 18:03

0xAliHn


People also ask

How do you use kotlin handler postDelayed?

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.

What is postDelayed?

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.

What is Handler in Kotlin?

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.


1 Answers

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) 
like image 144
s1m0nw1 Avatar answered Sep 30 '22 22:09

s1m0nw1