35

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?

0xAliHn
  • 18,390
  • 23
  • 91
  • 111

2 Answers2

54

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)
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • Instantiating Handler with the empty constructor is deprecated now. Initialize it, for example, with Looper, like here: https://stackoverflow.com/a/62477706/8716408 – Michael Abyzov Sep 10 '20 at 11:23
26

Handler() is depreciated now in place of it we have to use Handler(Looper.getMainLooper())

Handler(Looper.getMainLooper()).postDelayed(object : Runnable {
                    override fun run() {
                        TODO("Not yet implemented")
                    }
                },200)
Tushar Pandey
  • 4,557
  • 4
  • 33
  • 50