Hugo Costa
04/07/2025, 2:05 PMwithContext
. I find myself using MDC a lot like
val validationId = message.validationUniqueIdentifier
MDC.put("validationRequestId", validationId)
return withContext(MDCContext()) { ... }
and I'm interested in 2 things
1. Should I do withContext(MDCContext())
or withContext(coroutineContext + MDCContext())
, with coroutineContext being provided by the parent scope where I am running this?
2. Can I abstract this into something like below to make it faster to create?
suspend fun <T> withMDCContext(
parentContext: CoroutineContext,
block: suspend CoroutineScope.() -> T,
): T = withContext(parentContext + MDCContext()) { block() }
// depending on your answer, or ...
suspend fun <T> withMDCContext(block: suspend CoroutineScope.() -> T): T = withContext(MDCContext()) { block() }
Szymon Jeziorski
04/07/2025, 2:21 PMwithContext
by default creates a new context by merging current coroutine's context with context passed as parameter. Passing existing context isn't needed and would only be redundant
2. I don't see a reason not to. With first answer in mind, skip parentContext
in the function signature.Hugo Costa
04/07/2025, 2:21 PM