了解协程中的 cancelParent 函数
Understanding cancelParent function in coroutines
我正在阅读一些关于协程的源代码,运行进入这个函数;
private fun cancelParent(cause: Throwable): Boolean {
// CancellationException is considered "normal" and parent is not cancelled when child produces it.
// This allow parent to cancel its children (normally) without being cancelled itself, unless
// child crashes and produce some other exception during its completion.
if (cause is CancellationException) return true
if (!cancelsParent) return false
return parentHandle?.childCancelled(cause) == true
}
我不太明白的是第一行代码。感觉这与评论中所说的相矛盾。如果异常是 CancellationException
那么它是一个 "normal" 取消并且父项不应该被取消,对吧?但是,函数 returns true
读起来像 - "Ok, I'm gonna cancel the parent"。
顺便说一句,当我查看 supervisorScope
或 launch
、returns 时,函数中的其余部分 lines/checks 对我来说很有意义.
有人可以解释一下吗?
这是命名 return 值很有价值的情况之一。
如果您查看 usage of this code,您将看到以下内容:
// Now handle the final exception
if (finalException != null) {
val handled = cancelParent(finalException) || handleJobException(finalException)
if (handled) (finalState as CompletedExceptionally).makeHandled()
}
因此,true
并不像人们想象的那样 shouldParentBeCancelled?
,而是 wasCancellationAlreadyHandledOrShouldBeHandledByParent?
我正在阅读一些关于协程的源代码,运行进入这个函数;
private fun cancelParent(cause: Throwable): Boolean {
// CancellationException is considered "normal" and parent is not cancelled when child produces it.
// This allow parent to cancel its children (normally) without being cancelled itself, unless
// child crashes and produce some other exception during its completion.
if (cause is CancellationException) return true
if (!cancelsParent) return false
return parentHandle?.childCancelled(cause) == true
}
我不太明白的是第一行代码。感觉这与评论中所说的相矛盾。如果异常是 CancellationException
那么它是一个 "normal" 取消并且父项不应该被取消,对吧?但是,函数 returns true
读起来像 - "Ok, I'm gonna cancel the parent"。
顺便说一句,当我查看 supervisorScope
或 launch
、returns 时,函数中的其余部分 lines/checks 对我来说很有意义.
有人可以解释一下吗?
这是命名 return 值很有价值的情况之一。
如果您查看 usage of this code,您将看到以下内容:
// Now handle the final exception
if (finalException != null) {
val handled = cancelParent(finalException) || handleJobException(finalException)
if (handled) (finalState as CompletedExceptionally).makeHandled()
}
因此,true
并不像人们想象的那样 shouldParentBeCancelled?
,而是 wasCancellationAlreadyHandledOrShouldBeHandledByParent?