Coroutines Basics

Coroutines Basics

What is coroutines ?

  • is used to do suspendable computation
  • is a light weight thread
  • runs a block of code concurrently with rest of code

A coroutine is not bound to one thread which means it can suspend in one thread and resumes its execution in another thread.

Basic blocks

runBlocking

  • is a coroutine builder which bridges the regular code with the code within runBlocking {...} block

launch{...}

  • is a coroutine builder
  • launches a new coroutine which concurrently runs with the rest of code .

delay

  • suspending function
  • it suspends a coroutine for a specific amount of time eg: delay(2000L)

Code

fun main() = runBlocking {
    launch {
        delay(2000L)
        println("I am fine!")
    }
    println("How are you ?")
}

Suspend

  • suspend function can be use inside coroutines like regular functions but they can only call other suspending function.

Code

fun main() = runBlocking {
    launch {
       doReply()
    }
    println("How are you ?")
}

suspend fun doReply(){
    delay(2000L)
    println("I am fine!")
}

Scope Builder

  • Scope builders are one which is used to run coroutines inside a scope

runBlocking

  • blocks the current thread for waiting until it executes the block of code coroutines

coroutineScope

  • just suspends the block of code , releasing the underlying thread for other usage
  • we can call coroutineScope from any suspend function

Code

fun main() = runBlocking {
    doReply()
    println("Done")
}

suspend fun doReply() = coroutineScope {
    launch {
        delay(1000L)
        println("I am Fine")
    }
    println("How are you? ")
}

Concurrency

coroutineScope builder can be used inside any suspending functions to perform multiple concurrent operations

Code

fun main() = runBlocking {
    doReply()
    println("Done")
}

suspend fun doReply() = coroutineScope {
    /*launch 1*/
    launch {
        delay(1000L)
        println("I am Fine")
    }
    /*launch 2*/
    launch {
        delay(2000L)
        println("I am in native")
    }
    println("How are you? ")
    println("Where are you? ")
}

Code Explanation:

  • Both the launch{...} that is launch1 and launch2 is executed concurrently which means launch1 is executed at 1 second from start and launch 2 is executed at 2 seconds from start
  • launch1 and launch2 is executed concurrently at the same time .

Coroutines are light weight

  • Lets look at the following example
    fun main() =
      runBlocking {
          repeat(100_000) {
              launch {
                  delay(2000L)
                  println("Done!")
              }
          }
      }
    
    The above launches 100k coroutines and after 2 seconds Done! will be printed.

If we try the same with Java , it will throw OutOfMemoryError