Coroutine Builders Job
Explore how coroutine builders in Kotlin create Jobs and manage their parent-child relationships to maintain structured concurrency. Understand how to use Jobs to monitor coroutine completion and implement synchronization. This lesson helps you grasp key mechanisms behind coroutine cancellation, exception handling, and waiting for coroutines to finish using the join method and children properties.
We'll cover the following...
Every coroutine builder from the Kotlin coroutines library creates its own job. Most coroutine builders return their jobs so we can use them elsewhere. This is visible for launch, where Job is an explicit result type.
package kotlinx.coroutines.app
import kotlinx.coroutines.*
fun main(): Unit = runBlocking {
val job: Job = launch {
delay(1000)
println("Test")
}
}The type returned by the async function is Deferred<T>, and Deferred<T> also implements the Job interface so we can use it similarly.
Since Job is a coroutine context, we ...