Getting started with coroutines

So, let's take the following example into consideration:

    suspend fun longRunningTsk():Long {//(1) 
      val time = measureTimeMillis {//(2) 
        println("Please wait") 
        delay(2,TimeUnit.SECONDS)//(3) 
        println("Delay Over") 
      } 
      return time 
    } 
 
    fun main(args: Array<String>) { 
      runBlocking {//(4) 
        val exeTime = longRunningTsk()//(5) 
        println("Execution Time is $exeTime") 
      } 
    } 

We will inspect through the code, but let's first see the output:

Please wait 
Delay Over 
Execution Time is 2018 

So, now, let's understand the code. On comment (1), while declaring the function, we mark the function with the suspend keyword, which is used to mark a function as suspending, that is, while executing the function the program should wait for its ...

Get Reactive Programming in Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.