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

Patrick

12/13/2019, 8:48 AM
Is there a way to get the parent context of a coroutine (the context the coroutine has been launched from)?
o

octylFractal

12/13/2019, 9:03 AM
I don't know if it lets you get the context, but you can get the job via
coroutineContext[Job]!!.parent
p

Patrick

12/13/2019, 9:09 AM
I don’t have a parent property. How can I get the parent?
o

octylFractal

12/13/2019, 9:15 AM
hmm, it looks like that's not actually public. I guess it's just not possible then
l

louiscad

12/13/2019, 9:17 AM
Why do you want to do that?
p

Patrick

12/13/2019, 9:19 AM
I have a callback that I want to run in the original scope (e.g. Main) that it has been started from, not in the one that the task is running in. But I can’t just use launch(Dispatchers.Main) because I can’t be sure that it is always the main scope
o

octylFractal

12/13/2019, 9:20 AM
that sounds like it should be injected separately, rather than looking up the coroutine parents
and only if you're sure you want to violate structured concurrency there
p

Patrick

12/13/2019, 9:21 AM
I guess I could just provide the parent context via a constructor parameter, but it would be nicer if I could get the parent automatically
Actually I’m trying to follow structured concurrency because if I run something from the main thread, the callback should be also running in the main thread and not in Dispatchers.IO for example
o

octylFractal

12/13/2019, 9:22 AM
then just use
withContext(Dispatchers.Main)
that's the correct way to do that
p

Patrick

12/13/2019, 9:23 AM
But I only want to run it in the main thread if it has been started from the main thread
Not if it has been started from IO
Does that make sense?
l

louiscad

12/13/2019, 10:12 AM
Can you show some simplified code example of what you're doing so I can send you a version that tries to do what you want?
u

uli

12/13/2019, 12:35 PM
Turn the callback into a continuation (suspendCancelableCoroutine) and let the caller decide on the scheduler
p

Patrick

12/13/2019, 3:23 PM
Is there a way to do this without having to use suspend? The idea is that the application developer does not need to know about coroutines in this code. If they want to run the code from an Android Activity, they should not have to use any coroutine specific code.
u

uli

12/14/2019, 5:44 PM
If you are not called from a curoutine, how can you have a parent context?
30 Views