https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

kazuki tanida

02/05/2023, 11:44 AM
I want to modify ReactorContext or the context of reactor after a coroutine is created. For example, some
CoroutineContext
has a
ReactorContext
which wraps a
context of reactor
. In my case the context of reactor has two key/value pairs as the following image but I want to add one more pair to the current context mutably not immutable!
Anyway I want to modify ReactorContext or the context of reactor directly associated with a coroutine. Is it possible?
n

Nick Zois

02/05/2023, 1:30 PM
Adding information to the context make it available to
self
and spawned coroutines. So context modifications in the children may not be available to the parent.
I put here an issue, if you face the same let me know, I am also trying to solve it in SpringbootWorld. Well, you can add extra info to the ReactorContext, but I faced issues when I call other suspend-able methods in springboot @service, which somehow eliminates the context that I ve added. I haven’t investigated more on that, but if you are in springboot you may face similar issues. e.g. Lets say that I have a rest-controller, and I add the user id and span id in the reactor’s context, if I call a method to a service component, the context keys have erased.
k

kazuki tanida

02/05/2023, 5:55 PM
Adding information to the context make it available to
self
and spawned coroutines. So context modifications in the children may not be available to the parent.
I see. That make sense. 😢
I put here an issue, if you face the same let me know, I am also trying to solve it in SpringbootWorld. Well, you can add extra info to the ReactorContext, but I faced issues when I call other suspend-able methods in springboot
@service
, which somehow eliminates the context that I ve added. I haven’t investigated more on that, but if you are in springboot you may face similar issues. e.g. Lets say that I have a rest-controller, and I add the user id and span id in the reactor’s context, if I call a method to a service component, the context keys have erased.
I also use Kotlin with Spring Boot (WebFlux) and in
WebFilter
and I found I can add extra info to the context of Reactor which belongs to ReactorContext. (but I want to modify it after WebFilter…) like this
Copy code
@Component
class HttpRequestWebFilter : WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        return chain.filter(exchange)
                .contextWrite { ctx ->
                    ctx.put(SomeClass::class.java, someValue)
                }
    }
}
I found it works in suspending function in some bean class.
Copy code
coroutineContext[ReactorContext].context.get(SomeClass::class.java)
// will result in someValue
41 Views