https://kotlinlang.org logo
#spring
Title
# spring
d

Dariusz Kuc

09/26/2019, 4:25 AM
hello! does anyone know what is the proper way to invoke coroutines from Spring WebFilters? e.g. something like this works and populates the context as expected
Copy code
class FooFilter : WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> = mono {
        foo()
    }.flatMap { foo ->
        chain.filter(exchange).subscriberContext { it.put("foo", foo) }
    }
    
    suspend fun foo(): Foo { ... }
}
problem arise if there is another webfilter populates subscriber context BEFORE this filter and we would like to also access it in
foo()
with latest spring boot and coroutines we do have a nice interop between them, e.g. we can access reactor context from coroutine context
Copy code
val bar = coroutineContext[ReactorContext]?.context?.get<Bar>("bar")
but in the example above, when executing
FooFilter
our reactor context is empty
any ideas/suggestions?
so doing it like this
Copy code
Mono.subscriberContext()
    .flatMap { ctx ->
        val foo = runBlocking(ctx.asCoroutineContext()) {
          foo()
        }
        chain.filter(exchange).subscriberContext { it.put("foo", foo) }
    }
seems to work... but that
runBlocking
there seems just wrong
... weird... original one using
mono { foo() }
started working for me
nvm
46 Views