3

我正在使用 KotlinArrow以及来自. 我想做的是将Mono实例转换为Eitherspring-webflux

在响应成功或返回错误时Either调用创建实例。Either.right(..)WebClientEither.left(..)WebClient

我正在寻找的是一种Mono类似于Either.fold(..)的方法,我可以在其中映射成功和错误的结果并返回与 a 不同的类型Mono。像这样的东西(伪代码不起作用):

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

一个人应该怎么走?

4

2 回答 2

4

没有fold方法 onMono但您可以使用两种方法实现相同的目的:maponErrorResume. 它会是这样的:

val either : Either<Throwable, ClientResponse> = 
               webClient().post()
                          .exchange()
                          .map { Either.right(it) }
                          .onErrorResume { Either.left(it).toMono() }
于 2018-04-25T10:20:00.287 回答
2

我不太熟悉 Arrow 库,也不熟悉它的典型用例,所以我将在这里使用 Java 片段来说明我的观点。

首先,我想首先指出这种类型似乎是阻塞的,而不是懒惰的(不像Mono)。将 aMono转换为该类型意味着您将使代码阻塞,并且您不应该这样做,例如,在 Controller 处理程序的中间,否则您将阻塞整个服务器。

这或多或少相当于:

Mono<ClientResponse> response = webClient.get().uri("/").exchange();
// blocking; return the response or throws an exception
ClientResponse blockingResponse = response.block();

话虽如此,我认为您应该能够通过调用它和它周围的块来将 a 转换Mono为该类型,或者首先将其转换为第一个,例如: block()try/catchCompletableFuture

Mono<ClientResponse> response = webClient.get().uri("/").exchange();
Either<Throwable, ClientResponse> either = response
        .toFuture()
        .handle((resp, t) -> Either.fold(t, resp))
        .get();

可能有更好的方法来做到这一点(尤其是内联函数),但它们都应该Mono首先涉及阻塞。

于 2018-04-24T12:07:05.547 回答