Is there a way to get the parent context of a coro...
# coroutines
p
Is there a way to get the parent context of a coroutine (the context the coroutine has been launched from)?
o
I don't know if it lets you get the context, but you can get the job via
coroutineContext[Job]!!.parent
p
I don’t have a parent property. How can I get the parent?
o
hmm, it looks like that's not actually public. I guess it's just not possible then
l
Why do you want to do that?
p
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
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
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
then just use
withContext(Dispatchers.Main)
that's the correct way to do that
p
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
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
Turn the callback into a continuation (suspendCancelableCoroutine) and let the caller decide on the scheduler
p
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
If you are not called from a curoutine, how can you have a parent context?