WebFlux functional: How to detect an empty Flux and return 404?

前端 未结 4 1577
灰色年华
灰色年华 2020-12-30 10:03

I\'m having the following simplified handler function (Spring WebFlux and the functional API using Kotlin). However, I need a hint how to detect an empty Flux and then use n

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 10:55

    In addition to the solution of Brian, if you are not want to do an empty check of the list all the time, you could create a extension function:

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

    And call it like you do it for the Mono:

    return customerFlux().collectListOrEmpty()
                         .switchIfEmpty(notFound().build())
                         .flatMap(c -> ok().body(BodyInserters.fromObject(c)))
    

提交回复
热议问题