Get current `coroutineContext` inside a regular function

Hello,
I asked the following question in Stack Overflow: kotlin - How to get current `coroutineContext` from a non-suspend function? - Stack Overflow

But I am repeating here :slight_smile:

I would like to get the current coroutineContext inside a regular function declared as:

fun log(message: String)

If it is not running inside a coroutine I am fine will null.

Basically, instead of:

public suspend inline val coroutineContext: CoroutineContext

I need:

public inline val coroutineContext: CoroutineContext?

This is entirely for logging purposes. I need to log a certain element from the context (in some way this is similar how coroutine’s name is appended to Thread.currentThread().name for debugging).

Is this possible? Thanks!

No, it is not. Coroutine context. Non-suspending function does not have a context. You need to pass it explicitly to your function as parameter or receiver.

The way I solved it is to use ThreadLocal instead of CoroutineContext.Element to keep the value in question, then use asContextElement to have coroutine context manage the ThreadLocal. This is explained in the docs here: kotlinx.coroutines/coroutine-context-and-dispatchers.md at master · Kotlin/kotlinx.coroutines · GitHub

Then ThreadLocal is accessible both from suspend fun and fun. In this way, ThreadLocals seem more powerful than coroutine context, since it is accessible from everywhere.

Technically, it would be even possible to expose coroutineContext as a ThreadLocal.