如果其中之一为空,则发布者串联

Publisher concatenation if one of them is empty

我正在尝试连接两个发布者,但我知道 this 可以为空,我希望结果也为空。

fun Flux<String>.prefixWith(rhs: Mono<String>) = rhs
    .flux()
    .concatWith(this)

正如预期的那样 returns rhs。如果 this 为空,如何 return 清空 Flux

可以用FluxhasElements()方法(doc)判断通量是否有元素,然后用flatMapMany,return 如果存在元素则为串联,如果不存在元素则为空通量本身。

fun Flux<String>.prefixWith(rhs: Mono<String>) = this.hasElements().flatMapMany<String> {
    if (it) {
        rhs.concatWith(this) //when the flux has elements
    } else {
        this //this would be empty flux
    }
}