kotlinspring-webfluxproject-reactorarrow-kt

Transforming a Spring Webflux Mono to an Either, preferably without blocking?


I'm using Kotlin and Arrow and the WebClient from spring-webflux. What I'd like to do is to transform a Mono instance to an Either.

The Either instance is created by calling Either.right(..) when the response of the WebClient is successful or Either.left(..) when WebClient returns an error.

What I'm looking for is a method in Mono similar to Either.fold(..) where I can map over the successful and erroneous result and return a different type than a Mono. Something like this (pseudo-code which doesn't work):

val either : Either<Throwable, ClientResponse> = 
                   webClient().post().exchange()
                                .fold({ throwable -> Either.left(throwable) },
                                      { response -> Either.right(response)})

How should one go about?


Solution

  • There is no fold method on Mono but you can achieve the same using two methods: map and onErrorResume. It would go something like this:

    val either : Either<Throwable, ClientResponse> = 
                   webClient().post()
                              .exchange()
                              .map { Either.right(it) }
                              .onErrorResume { Either.left(it).toMono() }