Intermediate 8 min readKotlin 2.0
Kotlin Coroutine Scope — Structured Concurrency
A coroutine scope defines the lifetime of coroutines. Structured concurrency means children belong to a parent and are cancelled together.
What You Will Learn
- Define parent-child coroutine relationships
- Use coroutineScope { } to wait for children
- Understand cancellation propagation
- Compare coroutineScope vs supervisorScope
- Relate scopes to Android viewModelScope
Structured Concurrency
Every coroutine has a parent. When the parent is cancelled, children are cancelled too. This prevents leaked work when a screen closes or a request times out.
coroutineScope Waits for Children
kotlin
import kotlinx.coroutines.*
fun main() = runBlocking {
coroutineScope {
launch { delay(200); println("Child A") }
launch { delay(100); println("Child B") }
}
println("Scope finished")
}Output
Child B
Child A
Scope finished
coroutineScope suspends until all children complete. B finishes before A because of shorter delay.
Dependency required:
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")Cancellation Propagation
Cancelling a scope cancels every child launched inside it. This is how viewModelScope stops work when a ViewModel is cleared.
Cancel a Scope
kotlin
import kotlinx.coroutines.*
fun main() = runBlocking {
val scope = CoroutineScope(Dispatchers.Default)
scope.launch { delay(500); println("Should not print") }
delay(50)
scope.cancel()
delay(600)
println("Done")
}Output
Done
scope.cancel() stops the child before it can print. Only "Done" appears.
Practice Exercise
Exercisemultiple choice
What happens when a parent coroutine scope is cancelled?
Quick Quiz
Quick Quiz
What does coroutineScope { } do?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-19Kotlin 2.0
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review