协程层次结构中的取消传播
理解取消如何在父子协程关系中传播。
协程层次结构中的取消传播 是 CoddyKit 上的免费 Kotlin Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Kotlin Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Kotlin Academy 课程共包含 4 节课。
父子关系
当协程使用 launch 启动另一个协程时,子协程会加入父级的 Job。取消父协程会取消所有子协程。
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
launch { delay(1000); println("child 1") }
launch { delay(1000); println("child 2") }
delay(1000)
println("parent")
}
delay(50)
parent.cancel()
parent.join()
println("All cancelled")
}子协程失败会取消父协程
如果子协程抛出非取消异常,它会取消父协程及所有同级协程——这是默认的 Job 行为。
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
launch {
delay(50)
throw RuntimeException("child failed")
}
launch {
delay(1000)
println("sibling — never prints")
}
}
} catch (e: RuntimeException) {
println("Caught: ${e.message}")
}
}取消不会向上层传播
取消子协程不会取消父协程。只有未处理的异常才会向上传播。父协程可以随时取消子协程。
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
val child = launch {
delay(1000)
println("child done")
}
delay(50)
child.cancel() // cancels child
child.join()
println("parent still running") // parent is fine
}
parent.join()
}coroutineScope 与 GlobalScope
coroutineScope 会创建子作用域,取消和错误都会传播。GlobalScope 会创建没有父级的孤立协程——请避免在生产环境中使用它。
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
launch { delay(50); throw RuntimeException("error") }
}
} catch (e: Exception) {
println("coroutineScope propagated: ${e.message}")
}
// GlobalScope.launch { } would NOT propagate to runBlocking
}取消子树
每个 launch 或 async 都会返回一个 Job。取消某个作业即可取消它的整个子树,包括其中嵌套启动的协程。
import kotlinx.coroutines.*
fun main() = runBlocking {
val root = launch {
launch {
launch { delay(1000); println("deep") }
delay(1000)
}
}
delay(50)
root.cancel()
root.join()
println("Whole subtree cancelled")
}cancel() 之后调用 join()
请始终在 cancel() 之后调用 join(),等待协程及其子协程完全停止后再继续执行。
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try { delay(1000) }
finally { println("cleanup ran") }
}
delay(50)
job.cancel()
job.join() // waits for finally to complete
println("Proceeded after join")
}cancelAndJoin()
job.cancelAndJoin() 是一种便捷调用,会先取消再加入等待,其效果等同于 cancel() + join()。
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try { delay(1000) }
finally { println("cleanup") }
}
delay(50)
job.cancelAndJoin() // cancel + join in one call
println("Done")
}通过异步任务的传播
使用 async 时,异常会存储在 Deferred 中,并在调用 await() 时抛出。如果未被捕获,它们仍会传播到父协程。
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
val d = async { throw RuntimeException("async fail") }
d.await() // rethrows here
}
} catch (e: RuntimeException) {
println("Caught from async: ${e.message}")
}
}结构化并发的保证
结构化并发保证作用域结束时,其所有子协程也都已结束。不会有协程泄漏——它们要么完成,要么被取消。
import kotlinx.coroutines.*
suspend fun doWork() = coroutineScope {
launch { delay(100); println("work 1") }
launch { delay(200); println("work 2") }
// both children complete before doWork returns
}
fun main() = runBlocking {
doWork()
println("All work done")
}取消传播图
层级关系如下:取消父协程 → 取消所有子协程。取消子协程 → 只影响该子树。子协程抛出异常 → 取消父协程 → 取消同级协程。
import kotlinx.coroutines.*
fun main() = runBlocking {
// Parent
launch {
val c1 = launch { delay(1000); println("c1") } // child 1
val c2 = launch { delay(1000); println("c2") } // child 2
delay(50)
c1.cancel() // only c1 cancelled
c1.join()
println("c2 still active: ${c2.isActive}")
c2.cancelAndJoin()
}.join()
}安卓中 CoroutineScope 的生命周期
在安卓中,ViewModel 被清除时,viewModelScope 会被取消。所有已启动的协程都会自动取消——无需手动清理。
import kotlinx.coroutines.*
// Pseudocode:
// class MyViewModel : ViewModel() {
// fun load() = viewModelScope.launch {
// val data = repo.fetch() // cancelled if VM cleared
// _state.value = data
// }
// }
fun main() = runBlocking { println("viewModelScope cancels on ViewModel.onCleared()") }快速检查
在普通 Job 下,如果子协程抛出未处理的异常,同级协程会发生什么?
回顾
父协程的取消会级联到所有子协程。子协程的失败会传播到父协程和同级协程(使用普通 Job 时)。请使用 cancelAndJoin() 进行干净的拆除。结构化并发可以确保不会发生协程泄漏。
常见问题解答
「协程层次结构中的取消传播」课时是免费的吗?
是的 — 「协程层次结构中的取消传播」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Kotlin Academy 课程的其余内容,请升级到 CoddyKit PRO。 Kotlin Academy 课程共包含 4 节课。
「协程层次结构中的取消传播」这节课中我会学到什么?
理解取消如何在父子协程关系中传播。 你通过在浏览器中直接运行的动手代码来练习 Kotlin Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Kotlin Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Kotlin Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「协程层次结构中的取消传播」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Kotlin Academy 课中编写并运行代码吗?
能。每节 Kotlin Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 协作式取消:isActive 与 ensureActive
- withTimeout 与 withTimeoutOrNull
- 使用 finally 与 NonCancellable 清理资源
- 协程层次结构中的取消传播