13

我有以下简化的处理程序函数(Spring WebFlux 和使用 Kotlin 的功能 API)。但是,我需要提示如何检测空的 Flux,然后在 Flux 为空时将 noContent() 用于 404。

fun findByLastname(request: ServerRequest): Mono<ServerResponse> {
    val lastnameOpt = request.queryParam("lastname")
    val customerFlux = if (lastnameOpt.isPresent) {
        service.findByLastname(lastnameOpt.get())
    } else {
        service.findAll()
    }
    // How can I detect an empty Flux and then invoke noContent() ?
    return ok().body(customerFlux, Customer::class.java)
}
4

4 回答 4

26

从一个Mono

return customerMono
           .flatMap(c -> ok().body(BodyInserters.fromObject(c)))
           .switchIfEmpty(notFound().build());

从一个Flux

return customerFlux
           .collectList()
           .flatMap(l -> {
               if(l.isEmpty()) {
                 return notFound().build();

               }
               else {
                 return ok().body(BodyInserters.fromObject(l)));
               }
           });

请注意,collectList在内存中缓冲数据,因此这可能不是大列表的最佳选择。可能有更好的方法来解决这个问题。

于 2017-08-28T08:17:03.170 回答
9

使用Flux.hasElements() : Mono<Boolean>功能:

return customerFlux.hasElements()
                   .flatMap {
                     if (it) ok().body(customerFlux)
                     else noContent().build()
                   }
于 2019-05-05T02:04:51.777 回答
6

除了 Brian 的解决方案,如果你不想一直对列表做空检查,你可以创建一个扩展函数:

fun <R> Flux<R>.collectListOrEmpty(): Mono<List<R>> = this.collectList().flatMap {
        val result = if (it.isEmpty()) {
            Mono.empty()
        } else {
            Mono.just(it)
        }
        result
    }

并像为 Mono 那样调用它:

return customerFlux().collectListOrEmpty()
                     .switchIfEmpty(notFound().build())
                     .flatMap(c -> ok().body(BodyInserters.fromObject(c)))
于 2018-01-11T20:20:53.130 回答
6

我不确定为什么没有人谈论使用 Flux.java 的 hasElements() 函数,它会返回一个 Mono。

于 2019-04-24T12:00:47.323 回答