0
0
KotlinHow-ToBeginner · 3 min read

How to Use coroutineScope in Kotlin for Structured Concurrency

In Kotlin, coroutineScope is a suspending function that creates a new coroutine scope and waits for all launched child coroutines inside it to complete before resuming. It helps manage concurrency by ensuring structured execution within a suspending function.
📐

Syntax

The coroutineScope function is called inside a suspending function and takes a block of code where you can launch child coroutines. It suspends the current coroutine until all child coroutines finish.

  • coroutineScope { ... }: Creates a new scope.
  • Inside the block, you can launch or async coroutines.
  • The function itself is suspend, so it must be called from another suspending function or coroutine.
kotlin
suspend fun example() {
    coroutineScope {
        // launch child coroutines here
    }
}
💻

Example

This example shows how coroutineScope waits for all launched coroutines inside it to complete before printing the final message.

kotlin
import kotlinx.coroutines.*

suspend fun main() {
    println("Start")
    coroutineScope {
        launch {
            delay(500)
            println("Task 1 done")
        }
        launch {
            delay(300)
            println("Task 2 done")
        }
    }
    println("All tasks completed")
}
Output
Start Task 2 done Task 1 done All tasks completed
⚠️

Common Pitfalls

1. Calling coroutineScope outside a suspending function or coroutine: This causes a compile error because coroutineScope is a suspending function.

2. Forgetting that coroutineScope waits for all child coroutines: If you launch coroutines outside coroutineScope, they may not complete before the function returns.

3. Using GlobalScope.launch inside coroutineScope: This breaks structured concurrency because GlobalScope coroutines are not tied to the scope and may outlive it.

kotlin
/* Wrong: calling coroutineScope outside suspend function */
// coroutineScope {
//     launch { println("Won't compile") }
// }

/* Right: inside suspend function */
suspend fun correctUsage() {
    coroutineScope {
        launch { println("Works fine") }
    }
}
📊

Quick Reference

  • coroutineScope suspends until all child coroutines complete.
  • Use inside suspending functions or coroutines only.
  • Launch child coroutines with launch or async inside the block.
  • Helps keep concurrency structured and predictable.

Key Takeaways

coroutineScope creates a new coroutine scope and waits for all child coroutines to finish before continuing.
It must be called from a suspending function or another coroutine.
Avoid launching coroutines in GlobalScope inside coroutineScope to maintain structured concurrency.
Use coroutineScope to manage concurrency safely and predictably within suspending functions.