Coroutine context

Coroutines always run in a context. All coroutine builders have context specified by default, and that context is available through the value coroutineContext, inside the coroutine body:

import kotlinx.coroutines.experimental.*

fun
main(args: Array<String>) = runBlocking {
println("run blocking coroutineContext = $coroutineContext")
println("coroutineContext[Job] = ${coroutineContext[Job]}")
println(Thread.currentThread().name)
println("-----")

val jobs = listOf(
launch {
println("launch coroutineContext = $coroutineContext")
println("coroutineContext[Job] = ${coroutineContext[Job]}")
println(Thread.currentThread().name)
println("-----")
},
async {
println("async coroutineContext = $coroutineContext")
println("coroutineContext[Job] = ${coroutineContext[Job]}")
println(Thread.currentThread().name)
println("-----")
},
launch(CommonPool) {
println("common launch coroutineContext = $coroutineContext")
println("coroutineContext[Job] = ${coroutineContext[Job]}")
println(Thread.currentThread().name)
println("-----")
},
launch(coroutineContext) {
println("inherit launch coroutineContext = $coroutineContext")
println("coroutineContext[Job] = ${coroutineContext[Job]}")
println(Thread.currentThread().name)
println("-----")
}
)

jobs.forEach { job ->
println("job = $job")
job.join()
}
}

Each coroutine context also includes CoroutineDispatcher that decides which thread the coroutine runs. Coroutines builders, such as async and launch, use the DefaultDispatcher dispatcher as default (in the current coroutines version, 0.2.1, DefaultDispatcher is equal to CommonPool; however, this behavior can change in the future).

The coroutine context can also hold values; for example, you can recover the coroutine's job by using coroutineContext[Job].

Coroutine contexts can be used to control its children. Our 1 million coroutines example can be reworked to join all its children:

fun main(args: Array<String>) = runBlocking {

val job = launch {
repeat(1_000_000) {
launch(coroutineContext) {
delay(1000)
print('.')
}
}
}

job.join()
}

Instead of each one of the million coroutines having its own context, we can set a shared coroutine context that actually comes from the external launch coroutine context. When we join the outer launch job, it joins all its coroutine children, too.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.35.72