Search code examples
kotlinspring-webfluxproject-reactorreactor

Send multiple Fluxes with different types in one response


If I have code like so:

data class Response(
  val a: String,
  val b: List<String>,
  val c: Int,
)

fun buildResponse(): Response {
  val a: Mono<String> = getA()
  val b: Flux<String> = getB()
  val c: Mono<Int> = getC()

  return Response(
    a = a.blockOptional().orElseThrow(),
    b = b.collectList().blockOptional().orElseThrow(),
    c = c.blockOptional().orElseThrow(),
  )
}

Is there a way to reactively return a Mono<Response> instead of blocking and returning the actual Response?


Solution

  • Sure - have a look at the Mono.zip operator, which will allow you to combine several publishers into a single Mono. The basic Mono.zip variants just return a tuple, but you can also specify your own class (Response in this case) as so:

    return Mono.zip(
            Function { eles: Array<Any> ->
                Response(eles[0] as String,
                        eles[1] as List<String>,
                        eles[2] as Int)
            },
            a, b.collectList(), c)