https://kotlinlang.org logo
#coroutines
Title
# coroutines
g

genovich

09/02/2020, 11:25 AM
Is there some way to get job from
CoroutineContext
by key and cancel it?
s

streetsofboston

09/02/2020, 11:46 AM
someCoroutineContext[Job]?.cancel()
g

genovich

09/02/2020, 11:51 AM
what if I want to retrieve concrete child job from context?
s

streetsofboston

09/02/2020, 11:55 AM
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

genovich

09/02/2020, 12:13 PM
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

streetsofboston

09/02/2020, 12:32 PM
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

genovich

09/02/2020, 12:34 PM
I see
@elizarov, what is Your suggestion from the creator’s point of view?
e

elizarov

09/02/2020, 1:24 PM
What exactly are you trying to achieve? What's the context of the stuff you are doing?
g

genovich

09/02/2020, 1:36 PM
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

elizarov

09/02/2020, 6:36 PM
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

genovich

09/02/2020, 6:56 PM
So I did =)
Thank you both for answers
💯 1
9 Views