Kotlin 将Spring Webflux单声道转换为双声道,最好不阻塞?
我正在使用Kotlin和fromKotlin 将Spring Webflux单声道转换为双声道,最好不阻塞?,kotlin,spring-webflux,project-reactor,arrow-kt,Kotlin,Spring Webflux,Project Reactor,Arrow Kt,我正在使用Kotlin和fromSpringWebFlux。我想做的是将一个实例转换为一个实例 当WebClient的响应成功时,通过调用earth.right(…)创建earth实例;当WebClient返回错误时,调用earth.left(…)实例 我正在寻找的是Mono中的一种方法,类似于我可以映射成功和错误的结果,并返回与Mono不同的类型。类似这样的代码(不起作用的伪代码): val或:或= webClient().post().exchange() .fold({throwable-
SpringWebFlux
。我想做的是将一个实例转换为一个实例
当WebClient
的响应成功时,通过调用earth.right(…)
创建earth
实例;当WebClient
返回错误时,调用earth.left(…)
实例
我正在寻找的是Mono
中的一种方法,类似于我可以映射成功和错误的结果,并返回与Mono
不同的类型。类似这样的代码(不起作用的伪代码):
val或:或=
webClient().post().exchange()
.fold({throwable->one.left(throwable)},
{response->any.right(response)}
应该怎么做呢?我不太熟悉Arrow库,也不太熟悉它的典型用例,所以我将在这里使用Java代码片段来说明我的观点 首先,我想首先指出,这种类型似乎是阻塞的,而不是懒惰的(不像
Mono
)。将<代码>单/<代码>转换为该类型意味着您将使代码阻塞,并且不应该这样做,例如,在控制器处理程序的中间,否则会阻塞整个服务器。
这大致相当于:
Mono<ClientResponse> response = webClient.get().uri("/").exchange();
// blocking; return the response or throws an exception
ClientResponse blockingResponse = response.block();
可能有更好的方法(尤其是内联函数),但它们首先都应该包括在
Mono
上进行阻塞。在Mono
上没有折叠
方法,但可以使用两种方法实现相同的效果:map
和onErrorResume
。事情会是这样的:
val either : Either<Throwable, ClientResponse> =
webClient().post()
.exchange()
.map { Either.right(it) }
.onErrorResume { Either.left(it).toMono() }
val或:或=
webClient().post()
.exchange()
.map{other.right(it)}
.onErrorResume{one.left(it.toMono()}
Mono<ClientResponse> response = webClient.get().uri("/").exchange();
Either<Throwable, ClientResponse> either = response
.toFuture()
.handle((resp, t) -> Either.fold(t, resp))
.get();
val either : Either<Throwable, ClientResponse> =
webClient().post()
.exchange()
.map { Either.right(it) }
.onErrorResume { Either.left(it).toMono() }