Is there any way to get child's coroutineContext e...
# coroutines
k
Is there any way to get child's coroutineContext elements of a scope job? ie. lets say i have a scope:
scope: CoroutineScope
and i have launched a job in that scope:
Copy code
val context = Dispatchers.Default + CoroutineActionId(id)
val newJob= scope.launch(context) { ... }
given that
CoroutineActionId(id)
is an
AbstractCoroutineContextElement
how can i reach it having only
scope
? I've tried like this:
Copy code
val children = scope.coroutineContext[Job]?.children
val activeAction = children?.firstOrNull { it[CoroutineActionId]?.id == id }
if (activeAction != null) {
    activeAction.cancelChildren()
    activeAction.join()
}
but after debugging i've realized that children of scope's
Job
are different than jobs refs returned from
launch
but the amount is correct
. It looks like i see actual job on scope's
val children = scope.coroutineContext[Job]?.children
list but when i try to get
CoroutineActionId
like this
Copy code
children?.forEach {
     println("#state: caid = "  + it[CoroutineActionId]?.id)
}
it doesn't exist
z
Jobs don’t know about any other context elements, at least not via public api. And jobs are the only part of the coroutine context that actually form a hierarchy.
k
can i tag / give an additional field (of some kind) to a job so i can identify it later using a scope i've started it with ?
z
Kotlin in general (and Java) don’t let you add fields to objects at runtime
k
i mean in a way you can currently create
coroutineContext
element