Persistent context for the coroutine. It is an indexed set of Element instances. An indexed set is a mix between a set and a map. Every element in this set has a unique Key.
public class My3CoroutineName( val name: String ) : AbstractCoroutineContextElement(My3CoroutineName) { public companion object Key : CoroutineContext.Key<My3CoroutineName>
override fun toString(): String = "CoroutineName($name)" }
public class My4CoroutineName( val name: String ) : AbstractCoroutineContextElement(My4CoroutineName) {
public companion object Key : CoroutineContext.Key<My4CoroutineName>
override fun toString(): String = "CoroutineName($name)" }
fun studyContext4() { val my3CoroutineName = My3CoroutineName("item3") val my4CoroutineName = My4CoroutineName("item4") val my5CoroutineName = My3CoroutineName("item5")
val newElement = (my3CoroutineName + my4CoroutineName) + my5CoroutineName
private fun testLaunchWithCatch() { lifecycleScope.launchWithCatch { while (isActive) { // do loop operate println(">>>>I'm do loop") delay(1000) } } }
我们发现即使activity退出了,协程依然在工作,>>>>I'm do loop会始终输出; 问题原因就在于,SupervisorJob()的加入导致了原先的父子结构发生了变化;他的继承关系是SupervisorJob–〉JobImpl–〉JobSupport–〉Job; 回忆下文章开头协程获取设置父Job的场景,代码在类AbstractCoroutine的初始化函数中,
1 2 3
init { if (initParentJob) initParentJob(parentContext[Job]) }