简体   繁体   中英

How to get current `coroutineContext` from a non-suspend function?

Say I have a logging function:

fun log(message: String)

Unfortunately, this function will be called both from coroutines and outside of coroutines. In case of coroutines, I would like to log additional information coming from coroutine context (for example, coroutine's name).

How can I achieve this?

These are my thoughts but I don't have a solution:

  • Somehow figure out inside log if it is inside a coroutine and get coroutineContext . Is this possible?
  • I could have two versions of log eg log and logSuspend . But how do I ensure the right one gets called? If I'm inside suspend , nothing prevents me from calling log by accident. Additionally, I may have a regular helper function. Which one should it call?
  • Maybe something with ThreadLocal , for example I could coroutineContext inside a ThreadLocal at some point, but how do I ensure it stays up to date?

Somehow figure out inside log if it is inside a coroutine and get coroutineContext. Is this possible?

I don't think there is a good solution for that.

I would create two log functions, first for general purpose, second - an extension function on CoroutineScope for coroutines:

fun log(message: String) {...}

fun CoroutineScope.log(message: String) {
    //here you can access coroutineContext
}

And if you call log function from the coroutine like this:

GlobalScope.launch {
    log("CoroutineScope.log")
}

the extension function will be called and you will have access to coroutineContext .

Note: GlobalScope is not recommended to use, it is just for demonstration purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM