-
Notifications
You must be signed in to change notification settings - Fork 22
Coroutines: Relationship between Scope and Context
Devrath edited this page Dec 31, 2023
·
4 revisions
- In the diagram, there are 3 levels.
- Top highest level is the parent level, which has 4 children. now all 3 have the same context as the parent since they inherit the context.
- One child will have a different context since it has overridden the context to a different one.
- In the output
InnermostCoroutine2
the name is modified, but the rest all will have the same context inherited
fun scopeAndContextRelationshipDemo() {
viewModelScope.launch(CoroutineName("Pikachuu")) {
val name = coroutineContext[CoroutineName]?.name
println("OuterMostCoroutine:-> $name")
launch {
val name = coroutineContext[CoroutineName]?.name
println("InnerCoroutine1:-> $name")
launch {
val name = coroutineContext[CoroutineName]?.name
println("InnermostCoroutine1:-> $name")
}.join()
}.join()
launch {
val name = coroutineContext[CoroutineName]?.name
println("InnerCoroutine2:-> $name")
launch(CoroutineName("Goku ")) {
val name = coroutineContext[CoroutineName]?.name
println("InnermostCoroutine2:-> $name")
}.join()
}.join()
}
}
OuterMostCoroutine:-> Pikachuu
InnerCoroutine1:-> Pikachuu
InnermostCoroutine1:-> Pikachuu
InnerCoroutine2:-> Pikachuu
InnermostCoroutine2:-> Goku