Member-only story

5 Hidden Secrets of Kotlin Coroutines: I wish I Knew It Earlier🚀

Jayant Kumar🇮🇳
4 min readMar 12, 2025

--

Photo by Sander Sammy on Unsplash

Link For Non-Members

Kotlin coroutines are a powerful tool for writing asynchronous and concurrent code. Once you grasp the basics, you’ll discover there are many advanced features and best practices that can take your coroutine game to the next level. Here are 5 hidden secrets that can help you write cleaner, more efficient, and more maintainable asynchronous code.

1). CoroutineScope vs. SupervisorScope

In Kotlin, both coroutineScope and supervisorScope are used to structure concurrency by launching child coroutines. However, their error handling differs:

  • coroutineScope: If any child coroutine fails, the entire scope is cancelled, which means all other children are cancelled as well.
  • supervisorScope: A failure in one child coroutine does not affect its siblings; they continue running independently.

Example with coroutineScope

In this example, if any child fails, the entire scope cancels, and remaining children do not complete.

import kotlinx.coroutines.*

fun main() = runBlocking {
try {
coroutineScope {
launch {
delay(100)
println("coroutineScope: Child 1 completed")
}
launch {
delay(50)
println("coroutineScope: Child 2 throwing exception")
throw Exception("Error in Child 2")
}
launch {
delay(200)
println("coroutineScope: Child 3 completed")
}
}
} catch (e: Exception) {
println("coroutineScope: Caught exception: ${e.message}")
}
}

--

--

Jayant Kumar🇮🇳
Jayant Kumar🇮🇳

Written by Jayant Kumar🇮🇳

Hello My name is Jayant Kumar, I am a software Engineer , specialist in Mobile Development (Android , IOS , Flutter , React Native) from India 🇮🇳

No responses yet

Write a response