Unresolved reference: coroutineContext


Trying to test coroutines on my code-base.
Finding that when i try a launch or async call with coroutineContext (inherit from parent) as the context, the compiler pops an error that “Unresolved reference: coroutineContext”. Is there something that am missing here?
I am using 1.2.41 version of the language and on JDK-8


It looks like coroutineContext is made visible only if the parent coroutine is colocated on the same class. If i start a coroutine on class-A, which in-turn calls a method on class-B which starts another coroutine and if i want to run that coroutine on class-B on the same context of its parent from class-A, it doesn’t allow for that right now.


Ok. I don’t have that problem. Are you inside of a suspend function? Also make sure you import kotlin.coroutines.experimental.coroutineContext.


I am on a coroutine but not on a ‘suspended’ function call hierarchy at that place in code. If this is just a missing import, wouldn’t Idea provide that fix option?


As far as I know there are 2 ways to access the coroutineContext of the executing coroutine.
One is using the CoroutineScope. Functions like launch or runBlocking, etc give you access to this.
The other way is to use the coroutineContext property which is declared as suspend val which means you can only call it from a suspend function.


I see. Since coroutines suspend only on encountering a suspending low level function (like yield, await, send, receive…), this makes setting up the right confinement difficult for use-cases where those suspension points are not hit yet. I have rewired my design to avoid this situation (may be my initial design was not in harmony with how these should be setup).
Thanks for your help.


You don’t need to have hit a suspension point. But all of the code needs to be suspendable. A coroutine context is created by the launching function (eg launch or async). This is then used to create the coroutine. A suspend function has a hidden extra parameter in the context. This is made visible by the couroutineContext extension function. You can also write your own suspension functions, for example using suspendCoroutine. This will then give you access to a coroutine object that you can invoke to resume the coroutine from whereever it was.