【问题标题】:Kotlin coroutine Job's join methodKotlin协程Job的join方法
【发布时间】:2021-03-29 22:06:29
【问题描述】:

我发现 join 方法的文档很奇怪:

特别是,它意味着父协程调用 join 使用 launch(coroutineContext) { ... 如果孩子崩溃了,生成器会抛出 CancellationException, 除非在 上下文。

我不确定 CoroutineExceptionHandler 是否会对 CancellationException 产生影响。 示例:

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("CoroutineExceptionHandler got $exception")
    }
    val job = GlobalScope.launch(handler) {
        val inner = launch { // all this stack of coroutines will get cancelled
            throw IOException() // the original exception
        }
        try {
            inner.join()
        } catch (e: CancellationException) {
            println("handle join")
        }
    }
    job.join()
}

输出:

handle 
join CoroutineExceptionHandler got java.io.IOException

所以基本上 CancellationException 仍然会被抛出,无论是否安装了任何处理程序。 我说的对吗?

【问题讨论】:

  • 是的,我认为文档是错误的。除了顶级协程上下文(其Job 元素没有父级)之外,协程异常处理程序在任何地方都被忽略。

标签: android kotlin kotlin-coroutines


【解决方案1】:

是的。你的 innerJob 仍然会抛出一个CancellationException,而在你的外部工作中你会遇到崩溃,因为你不处理 exception

见:https://pl.kotl.in/1Uqw8nmNS

【讨论】:

  • 所以文档声明不正确,对吧?
猜你喜欢
  • 2020-05-26
  • 2018-04-12
  • 2018-05-13
  • 1970-01-01
  • 2021-07-31
  • 2021-08-01
  • 2019-02-19
  • 1970-01-01
相关资源
最近更新 更多