Is there some way to get job from `CoroutineContex...
# coroutines
g
Is there some way to get job from
CoroutineContext
by key and cancel it?
s
someCoroutineContext[Job]?.cancel()
g
what if I want to retrieve concrete child job from context?
s
A CoroutineContext has (at most) one Job. To examine child-jobs, get the main/parent Job (like in my example) and access the
children
property on it.
g
I want to associate each started Job with some key to find and cancel them later. What is better: to have
Map<Any, Job>
, or to add new
Element
to
CoroutineContext
?
Or there may be any better solution?
s
In my opinion, cache each Job (Deferred) returned by launch/async in a Map, like your first suggestion. An Element in CoroutineContext is not like a map. It is a Unique Type Set, ie you can have only one value of an Element-type in a CoroutineContext. This means, for example, you can't store 2 Jobs in a CoroutineContext.
g
I see
@elizarov, what is Your suggestion from the creator’s point of view?
e
What exactly are you trying to achieve? What's the context of the stuff you are doing?
g
I want to cancel concrete Jobs in
CoroutineScope
that have been launched earlier. You can treat it as a system that can emit signals like start Job or stop Job by token. I can explain this better in DM, if You want.
e
If you want to cancel them from "outside", from some control coroutine that is launching them, then the simplest way is to store somewhere the result of the
launch { .. }
function that returns a
Job
that you can call
cancel()
on.
g
So I did =)
Thank you both for answers
💯 1