Search code examples
springkotlincoroutinespring-webfluxkotlinx.coroutines

Kotlin coroutines and Spring Framework 5 reactive types


Kotlin coroutines allow to execute non-blocking code by returning Deferred value. This is really useful to make non-blocking code while using blocking methods (from a library for example).

Spring 5 allows to use Mono and Flux into the framework. The big interest that I see is the ability to serialize instances of these two types and send it back as response when someone call a controller endpoint.

One of the big point of Spring 5 is to have an specific support for Kotlin (router, bean declaration, ...), but I cannot find informations about the possible interactions between Kotlin coroutines and Spring 5 reactive types.

Is there any way to combine the advantages of these features?

  • converting Deferred into Mono/Flux?
  • having a Deferred as response type of Spring controller methods ?

If no, in which cases do coroutine make sense if we have Spring 5 reactive types?


Solution

  • As of version 5.2 (still work in progress), Spring Framework provides official support for coroutines. I have written a detailed blog post that explains how Mono and Flux types map to suspending functions, Deferred and Kotlin Flow types. You can also find more details in the coroutines section of Spring Framework 5.2 reference documentation.