在Flux 为空的情况下如何调用方法(消费者(,例如,如果 flux 为空,我想记录消息
我看到两种实现它的方法:
- 利用
switchIfEmpty()
然后,您的代码片段将具有以下表示形式:
.switchIfEmpty(Flux.empty().doOnComplete(() -> log.info("there were no elements")))
- 另一个选项是
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>