Hello, quick question on `withContext` . I find my...
# coroutines
h
Hello, quick question on
withContext
. I find myself using MDC a lot like
Copy code
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?
Copy code
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() }
s
1.
withContext
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.
h
Great! Exactly what I wanted to confirm, thanks 🙂