【发布时间】:2019-02-25 16:15:59
【问题描述】:
最近,我将 Kotlin Coroutines 从实验性升级到 1.1.1,遇到了 job.cancel() 在新版本中工作方式不同的问题。
这是带有实验协程的代码:
fun <R : Any, T : Deferred<R>> T.runAsync(
job: Job,
onSuccess: (result: R) -> Unit,
onFailed: (errorMsg: String?) -> Unit) {
launch(UI, parent = job) {
try {
val result = this@runAsync.await()
onSuccess(result)
} catch (e: Exception) {
onFailed(e.message)
}
}
}
这里是 1.1.1:
fun <R : Any, T : Deferred<R>> T.runAsync(
job: Job,
onSuccess: (result: R) -> Unit,
onFailed: (errorMsg: String?) -> Unit) {
GlobalScope.launch(Dispatchers.Main + job) {
try {
val result = withContext(Dispatchers.IO) {
this@runAsync.await()
}
onSuccess(result)
} catch (e: Exception) {
onFailed(e.message)
}
}
}
例如:
我的片段在协程运行期间被销毁并调用job.cancel()。
在实验协程中,onSuccess() 和 onFailed() 都不会被调用。
在 1.1.1 中:onFailed() 被调用,因为 JobCancellationException 被捕获
想办法加catch (e: JobCancellationException),但是不可能:
/**
* @suppress **This an internal API and should not be used from general code.**
*/
internal expect class JobCancellationException(
所以,问题是:如何处理/忽略JobCancellationException?
【问题讨论】:
标签: android kotlin kotlinx.coroutines