Kotlin First Coroutine
A coroutine is a piece of work that can pause and resume without holding on to a thread. runBlocking starts a coroutine block and lets a normal main function wait for it.
runBlocking on its own
runBlocking runs its block as a coroutine. The line after the block runs only after the block finishes.
import kotlinx.coroutines.*
fun main() {
runBlocking {
println("Inside the block")
}
println("After the block")
}A launched child and a joining parent
launch starts the child, and the parent prints its line first. join then pauses the parent, the child prints, and the parent continues.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val job = launch {
println("Child runs")
}
println("Parent waits")
job.join()
println("Parent continues")
}
}A child that prints two lines
The parent reaches join at once and waits there. The child prints both of its lines before the parent continues.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val job = launch {
println("Step one")
println("Step two")
}
job.join()
println("Child finished")
}
}Two children joined in turn
The second child is launched only after the first child finishes. Each join fixes the order of the prints around it.
import kotlinx.coroutines.*
fun main() {
runBlocking {
val first = launch {
println("First child")
}
first.join()
val second = launch {
println("Second child")
}
second.join()
println("Both children done")
}
}Example
import kotlinx.coroutines.*
fun main() {
runBlocking {
val job = launch {
println("Loading profile")
}
println("Request started")
job.join()
println("Profile ready")
}
println("Screen shown")
}Key points
- The import line import kotlinx.coroutines.* brings runBlocking, launch, and join into the file.
- runBlocking runs its block as a coroutine and makes main wait until the block finishes.
- launch starts a child coroutine inside the block and returns a handle for that child.
- join is called on the handle, and it pauses the parent until that child finishes.
- A launched child inside runBlocking runs when the parent reaches a waiting point such as join.
In this example, launch starts the child and the parent prints Request started first. join pauses the parent there, so the child prints Loading profile next. The parent then prints Profile ready, and the line after runBlocking prints Screen shown.
Note
The order of the prints in these examples is fixed by join, not by timing.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
What does join do in a coroutine program?