Refine PropagationContextElement

This commit apply several refinements to PropagationContextElement:
 - Capture the ThreadLocal when instantiating the
   PropagationContextElement in order to support dispatchers switching
   threads
 - Remove the constructor parameter which is not idiomatic and breaks
   the support when switching threads, and use instead the
   updateThreadContext(context: CoroutineContext) parameter
 - Make the kotlinx-coroutines-reactor dependency optional
 - Make the properties private

The Javadoc and tests are also updated to use the
`Dispatchers.IO + PropagationContextElement()` pattern performed
outside of the suspending lambda, which is the typical use case.

Closes gh-35469
This commit is contained in:
Sébastien Deleuze
2025-09-12 17:26:07 +02:00
parent 20e1149dde
commit 2faed3cdbb
4 changed files with 81 additions and 76 deletions
@@ -16,8 +16,9 @@
package org.springframework.docs.languages.kotlin.coroutines.propagation
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.core.PropagationContextElement
@@ -31,10 +32,15 @@ class ContextPropagationSample {
}
// tag::context[]
fun main() {
runBlocking(Dispatchers.IO + PropagationContextElement()) {
suspendingFunction()
}
}
suspend fun suspendingFunction() {
return withContext(PropagationContextElement(currentCoroutineContext())) {
logger.info("Suspending function with traceId")
}
delay(1)
logger.info("Suspending function with traceId")
}
// end::context[]
}