Job
- Kotlin course
- Advanced
- Lesson 3/83
- 5 min
Learn Job and Job hierarchy.
What is a Job?
When a coroutine starts, launch returns a Job. The Job represents that coroutine's lifecycle: active, completed, cancelled states.
Through the Job you can wait for the coroutine (join), cancel it (cancel) or ask whether it is still active (isActive). A Job can be a child of another Job; if the parent is cancelled, children are cancelled too. This structure makes cleanup after failure easy.
Waiting with join
job.join() suspends the current coroutine until the target coroutine completes. This is useful when you need ordered behavior: let a task finish, then continue.
Example: val job = launch { println("Work") }; job.join(); println("After"). Here Work prints first, then After. join also works on a cancelled Job; if the caller is not cancelled it stops waiting and continues.
Practice Wait with a Job and print
Inside runBlocking, write val job = launch { println("Running") }. Then wait with job.join() and print println("Done").
Starter code
// Use Job and join
// write here
fun main() = runBlocking {
}Sample solution
fun main() = runBlocking {
val job = launch {
println("Running")
}
job.join()
println("Done")
}Expected output
Running Done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Job parts
| Term | Meaning |
|---|---|
Job |
Lifecycle |
join |
Waits |
cancel |
Cancels |
isActive |
Is it running |
2 What does job.join() do?
- Starts a new coroutine
- Cancels the coroutine
- Waits until the coroutine finishes Correct answer
- Sleeps the thread
Explanation: join suspends the current coroutine until the target completes.
3 Complete the Job wait call
val job = launch { println("Work") }
job.____()
val job = launch { println("Work") }
job.join()
Explanation: join waits for the coroutine.