https://kotlinlang.org logo
Title
n

Nikky

11/13/2020, 12:03 PM
another questions about MDC and coroutineContext.. can i update a ThreadContextElement from inside the coroutine ? issue is this code seems natural
suspend fun doStuff() = withContext(MDCContext() + exceptionHandler()) {
   MDC.put("flow", "do-stuff")
   <http://logger.info|logger.info> { "doing stuff" } // mdc is fine here

   someSuspendFun()

   <http://logger.info|logger.info> { "done doing stuff" } // mdc was reset to the state of MDCContext ie. is empty
}
ideally what i would like to be able to do is update the MDCContext or update the
val contextMap: MDCContextMap
after i modify the MDC ( i tried, it fails in different ways ) or use a mechanism where the MDC is stored before doing a suspend call, so any changes are actually picked up TL;DR currently it leads to rather unnatural looking code and additional nesting or errors that are really hard to find
g

gildor

11/13/2020, 2:51 PM
You cannot use put, it will be rested after suspend
It mentioned in doc
n

Nikky

11/13/2020, 7:19 PM
i understand that is the current limitation, i was hoping someone with more indepth understanding of coroutine context switching might know of a better way to solve this than the current state of
MDCCOntext
or might know workarounds to update it
b

bezrukov

11/13/2020, 8:53 PM
Take the current MDCcontext, mutate and modify it, and wrap your suspend fun with one more withContext
n

Nikky

11/14/2020, 11:36 AM
exactly that extra withContext is what i was hoping to avoid, making code really a lot more annoying to write and read
g

gildor

11/15/2020, 12:27 PM
Maybe create an extension function for it?