kotlin - 如何传播来自作业的异常?

标签 kotlin kotlinx.coroutines

来自 What is the difference between launch/join and async/await in Kotlin coroutines :

launch is used to fire and forget coroutine. It is like starting a new thread. If the code inside the launch terminates with exception, then it is treated like uncaught exception in a thread -- usually printed to stderr in backend JVM applications and crashes Android applications. join is used to wait for completion of the launched coroutine and it does not propagate its exception. However, a crashed child coroutine cancels its parent with the corresponding exception, too.



join不传播异常,有没有办法等待 Job 的完成哪个呢?

例如。假设某个库方法返回 Job因为它假设它的用户不想传播异常,但事实证明确实有一个用户想要它;这个用户可以在不修改库的情况下获得它吗?

最佳答案

请使用加入+ invokeOnCompletion方法

代码将是这样的:

suspend fun awaitError(job: Job): Throwable? {
    val errorAwaiter = CompletableDeferred<Throwable?>();        

    job.invokeOnCompletion { errorAwaiter.complete(it) }

    require(job.IsActive) {
         "Job was completed for too fast, probably error is missed"
    }

    val errorRaised = errorAwaiter.await();

    return when(errorRaised) {
         is CancellationException -> null
         else -> errorRaised
    }
}

请注意,该代码会为快速作业引发错误,因此请小心。可能最好只返回 null在这种情况下(在我的例子中)。

关于kotlin - 如何传播来自作业的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47991935/

相关文章:

kotlin GlobalScope,runBlocking 在 kotlin.coroutines 中不可用。*

android - requestCode 代表什么?

kotlin - 如何使用 JUnit 5 在 Kotlin 中创建 TestContainers 基础测试类

android - 我/系统服务器: oneway function results will be dropped but finished with status OK and parcel size 4

android - 使用 Kotlin 的 fragment 中的 runOnUiThread() 方法

kotlin - 返回 Deferred 且名称不以 async 结尾的函数

kotlinx.coroutines - kotlin 协程 - 什么是默认范围?

kotlin - 生产者内部的监听器

logging - 如何为 KTOR 添加日志拦截器?

kotlin - 为什么挂起函数在finally中会抛出异常