首页 > 解决方案 > 如果其中之一为空,则发布者串联

问题描述

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

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

这只是rhs按预期返回。Flux如果为空,如何返回this空?

标签: kotlinreactor

解决方案


您可以使用hasElements()方法 ( doc )Flux来确定通量是否具有元素,然后使用flatMapMany, 如果存在元素则返回串联,如果不存在元素则返回空通量本身。

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

推荐阅读