有时候我们需要定义多个元素,我们可以使用+操作符实现
其原因就是因为参数实现了plus方法
如
@Test
fun `test CoroutineContext`() {
runBlocking<Unit> {
launch(Dispatchers.Default + CoroutineName("test")) {
println("I'm working in thread ${Thread.currentThread().name}")
}
}
}
上下文的继承
@Test
fun `test CoroutineContext extend`() = runBlocking<Unit> {
val scope = CoroutineScope(Job() + Dispatchers.IO + CoroutineName("test"))
val job = scope.launch {
println("${coroutineContext[Job]} ${Thread.currentThread().name}")
val result = async {
println("${coroutineContext[Job]} ${Thread.currentThread().name}")
"Ok"
}.await()
}
job.join()
}
launch协程里面的上下文就是 scope的上下文
那么async是launcher的子类
上下文的公式=默认值+继承的CoroutineContext+参数
协程的异常处理
@Test
fun `test CoroutineContext extend2`() = runBlocking<Unit> {
val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
println("Caught $throwable")
}
val scope = CoroutineScope(Job() + Dispatchers.Main + coroutineExceptionHandler)
val job = scope.launch(Dispatchers.IO) {
1 / 0
}
job.join()
}