I am trying to concatenate two publishers, but I know that this
can be empty and I want result be empty too.
fun Flux<String>.prefixWith(rhs: Mono<String>) = rhs
.flux()
.concatWith(this)
That just returns rhs
as expected. How to return empty Flux
if this
is empty?
You can use the hasElements()
method (doc) of Flux
to find out if the flux has elements or not, and then using flatMapMany
, return the concatenation if elements are present, or the empty flux itself if no elements are present.
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
}
}