WebFlux功能:如何检测一个空的通量并返回404?

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

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) } 

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在内存中缓冲数据,所以这可能不是大列表的最佳选择。 可能有更好的方法来解决这个问题。