副作用运算符(或类似)的情况下,如果为空助焊剂



在Flux 为空的情况下如何调用方法(消费者(,例如,如果 flux 为空,我想记录消息

我看到两种实现它的方法:

  1. 利用switchIfEmpty()

然后,您的代码片段将具有以下表示形式:

.switchIfEmpty(Flux.empty().doOnComplete(() -> log.info("there were no elements")))
  1. 另一个选项是hasElements()

尝试将下面的代码片段放在链的末尾

.hasElements()
.doOnNext(hasElements -> {
if (!hasElements) {
log.info("there were no elements");
}
})

这个是为你准备的:

/**
* Add behavior (side-effect) triggered when the {@link Flux} completes successfully.
* <p>
* <img class="marble" src="doc-files/marbles/doOnComplete.svg" alt="">
*
* @param onComplete the callback to call on {@link Subscriber#onComplete}
*
* @return an observed  {@link Flux}
*/
public final Flux<T> doOnComplete(Runnable onComplete) {

请参阅此 JavaDocs:

/**
* Represents an empty publisher which only calls onSubscribe and onComplete.
* <p>
* This Publisher is effectively stateless and only a single instance exists.
* Use the {@link #instance()} method to obtain a properly type-parametrized view of it.
* @see <a href="https://github.com/reactor/reactive-streams-commons">Reactive-Streams-Commons</a>
*/
final class FluxEmpty extends Flux<Object>

相关内容

最新更新