Mastering Kotlin Coroutines – Part 2

This is the part 2 of Mastering Kotlin Coroutines. In the previous article we have learned about some basic concept about Kotlin Coroutines, If you haven’t read that yet then please go and read it here.

Suspending function in kotlin coroutine

A suspending function is a function that can be paused and resumed later without blocking the thread on which it’s running. These functions are declared using the suspend keyword.

When a suspending function is called, it can perform long-running or asynchronous operations, such as network requests, file I/O, or database queries, without blocking the thread. Instead of blocking, the function can suspend its execution until the operation completes, allowing other code to continue running concurrently.

Suspension in Kotlin coroutines is cooperative, meaning it’s managed by the coroutine framework. When a suspending function encounters a suspension point, it can voluntarily suspend itself and release the thread it’s running on. Later, when the suspended operation completes, the function can resume execution from where it left off.

Let’s understand with an example

import kotlinx.coroutines.*

suspend fun task1() {
    println("First log statement in task1")
    
    // Pause the execution of this coroutine for 100 milliseconds
    delay(100)
    
    println("Second log statement in task1")
}

suspend fun task2() {
    println("First log statement in task2")
    
    // Pause the execution of this coroutine for 100 milliseconds
    delay(100)
    
    println("Second log statement in task2")
}

fun main() {
    // Start a coroutine for task1 within the main function
    GlobalScope.launch {
        task1()
    }

    // Start another coroutine for task2 within the main function
    GlobalScope.launch {
        task2()
    }

    // Keep the main function running to observe coroutine execution
    runBlocking {
        delay(200) // Delay for a short time to ensure coroutine execution
    }
}

Output

First log statement in task1
First log statement in task2
Second log statement in task1
Second log statement in task2

In this output:

  • Both task1() and task2() coroutines are launched concurrently. But first task1() logs as its first in sequence. Then for task1() a pause the execution of this coroutine for 100 milliseconds so task1() suspends its execution and free thread.
  • task2() coroutines started executing and task2 is printed “First log statement in task2” and then 100ms pause for task2() so again task2() coroutines suspends and free thread.
  • Since some work in task1()coroutines was pending so thread resumes task1() where it was suspended resulting in printing Second log statement in task1.
  • This is how suspending function works in coroutine framework.

Leave a Reply