CoroutineScope
- Kotlin course
- Advanced
- Lesson 1/83
- 5 min
Learn structured concurrency with CoroutineScope.
What is CoroutineScope?
A CoroutineScope is the scope in which coroutines live. Every coroutine belongs to a scope; cancelling the scope cancels all child coroutines.
In Kotlin runBlocking creates a scope and blocks the thread until the block completes. You start a new coroutine inside it with launch, which returns a Job. In this lesson you will write your first coroutine with runBlocking and launch.
Scope with runBlocking
runBlocking creates a new CoroutineScope and waits until the block completes. Inside it you start new coroutines with launch.
Example: runBlocking { launch { println("Running") } }. Here runBlocking is the outer frame and launch is one coroutine. The message inside println is printed; the program ends when runBlocking returns.
Practice Write your first coroutine
Open a scope with runBlocking. Start a coroutine with launch inside it that prints println("Hello coroutine"). The program ends when runBlocking finishes.
Starter code
// First coroutine with runBlocking and launch
// write here
fun main() {
}Sample solution
fun main() = runBlocking {
launch {
println("Hello coroutine")
}
}Expected output
Hello coroutine
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one starts a coroutine?
- launch Correct answer
- println
- main
- val
Explanation: launch starts a new coroutine.
2 Complete the CoroutineScope definition
val scope = CoroutineScope(____)
val scope = CoroutineScope(Dispatchers.Default)
Explanation: CoroutineScope takes a dispatcher.
3 Match the coroutine parts
| Term | Meaning |
|---|---|
CoroutineScope |
Scope |
launch |
Starts |
Job |
Return type |
runBlocking |
Waits |