首页 > 解决方案 > Spring WebFlux switchIfEmpty 返回不同的类型

问题描述

public Mono<ServerResponse> getMessage(ServerRequest request) {
    //this call returns Mono<ApiClientResponse>
    return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
            .switchIfEmpty(/* Here */)
}

请原谅代码稍微不完整,当我遇到这个问题时,我正在对其进行重组。要点是它在switchIfEmpty()调用中说 /* Here */ 的地方,编译器强制类型为Mono<ApiClientResponse>,但是当hystrixWrappedGetMessages()返回时Mono.empty()我想通过返回 204 来处理它Mono<ServerResponse>,否则我想返回 200。做到这一点?

理想情况下,我可以在 map 调用中检查它是否是 Mono.empty(),但如果它是空的 Mono,它似乎不会进入 map。考虑过使用可选项,但它们似乎不能很好地与 Monos 配合使用。

标签: javareactive-programmingspring-webfluxspring-webclientreactor-netty

解决方案


如果良好,您应该能够做出flatMap响应,如果Mono#empty返回 an,flatMap则将被忽略。

public Mono<ServerResponse> getMessage(ServerRequest request) {
    return apiClient.hystrixWrappedGetMessages(request.headers().asHttpHeaders(), request.queryParams())
        .flatMap(response -> {
            // Do your processing here
            return ServerResponse.ok().body( .... );
        }.switchIfEmpty(ServerResponse.noContent());
}

推荐阅读