英文:
Side effect operator (or a like) in case if empty flux
问题
如何在Flux为空的情况下调用方法(consumer),例如,如果Flux为空,我想记录消息。
英文:
How can I call a method (consumer) in case of Flux is empty, for example i want to log message if the flux is empty
答案1
得分: 2
- 利用
switchIfEmpty()
然后你的代码片段将具有以下表示:
.switchIfEmpty(Flux.empty().doOnComplete(() -> log.info("there were no elements")))
- 另一种选项是
hasElements()
。
尝试将以下代码片段放在您的链的末尾:
.hasElements()
.doOnNext(hasElements -> {
if (!hasElements) {
log.info("there were no elements");
}
})
英文:
I see two ways of achieving it:
- Utilise
switchIfEmpty()
Then your code snippet will have the following representation:
.switchIfEmpty(Flux.empty().doOnComplete(() -> log.info("there were no elements")))
- Another option is
hasElements()
.
Try to place the code snippet below somewhere at the end of your chain:
.hasElements()
.doOnNext(hasElements -> {
if (!hasElements) {
log.info("there were no elements");
}
})
答案2
得分: 1
This one is there for you:
/**
* 添加在{@link Flux}成功完成时触发的行为(副作用)。
* <p>
* <img class="marble" src="doc-files/marbles/doOnComplete.svg" alt="">
*
* @param onComplete 要在{@link Subscriber#onComplete}上调用的回调
*
* @return 观察到的{@link Flux}
*/
public final Flux<T> doOnComplete(Runnable onComplete) {
See this JavaDocs:
/**
* 代表一个仅调用onSubscribe和onComplete的空发布者。
* <p>
* 此发布者实际上是无状态的,仅存在一个实例。
* 使用{@link #instance()}方法获取适当的类型参数视图。
* @see <a href="https://github.com/reactor/reactive-streams-commons">Reactive-Streams-Commons</a>
*/
final class FluxEmpty extends Flux<Object>
英文:
This one is there for you:
/**
* 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) {
See this 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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论