Side effect operator(或类似的)在空的数据流情况下

huangapple go评论100阅读模式
英文:

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

  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");
    }
})
英文:

I see two ways of achieving it:

  1. Utilise switchIfEmpty()

Then your code snippet will have the following representation:

.switchIfEmpty(Flux.empty().doOnComplete(() -> log.info("there were no elements")))
  1. 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>

huangapple
  • 本文由 发表于 2020年1月3日 23:03:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定