How to Use coroutineScope in Kotlin for Structured Concurrency
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
launchorasynccoroutines. - The function itself is
suspend, so it must be called from another suspending function or coroutine.
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.
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") }
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.
/* 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
coroutineScopesuspends until all child coroutines complete.- Use inside suspending functions or coroutines only.
- Launch child coroutines with
launchorasyncinside 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.GlobalScope inside coroutineScope to maintain structured concurrency.coroutineScope to manage concurrency safely and predictably within suspending functions.