记录通量,直到单声道完成

时间:2019-06-11 12:32:52

标签: project-reactor

我有以下内容:

Flux<String> flux = ...
Mono<Void> mono = ...


Mono<Void> combined = operation(flux, mono);

它们表示并行发生的操作。

现在,我想将flux发出的所有元素打印到sysout,直到mono完成为止, 在这里使用什么运算符合适?

我已经尝试过:

final Disposable subscribe = flux.subscribe(System.out::println);
mono.doOnSuccessOrError((o, e) -> subscribe.dispose());

但是如果感觉很笨拙,我有一种更好的方法。有吗?

1 个答案:

答案 0 :(得分:0)

因此,Project Reactor提供了一些记录发射结果的方法:

您可以看到它的工作原理。

代码示例:

Flux<String> stringFlux = Flux.just("one", "two", "three")
            .doOnNext(s -> System.out.println("On next: " + s));
    Mono<String> stringMono = Mono.just("four");

    stringFlux = stringFlux.concatWith(stringMono)
            .map(s -> s + " hundred")
            .log();

    stringFlux.subscribe(s -> System.out.println("On next subscriber: " + s));

结果:

15:32:18.984 [main] INFO reactor.Flux.Map.1 - onSubscribe(FluxMap.MapSubscriber)
15:32:18.986 [main] INFO reactor.Flux.Map.1 - request(unbounded)
On next: one
15:32:19.005 [main] INFO reactor.Flux.Map.1 - onNext(one hundred)
On next subscriber: one hundred
On next: two
15:32:19.005 [main] INFO reactor.Flux.Map.1 - onNext(two hundred)
On next subscriber: two hundred
On next: three
15:32:19.005 [main] INFO reactor.Flux.Map.1 - onNext(three hundred)
On next subscriber: three hundred
15:32:19.006 [main] INFO reactor.Flux.Map.1 - onNext(four hundred)
On next subscriber: four hundred
15:32:19.007 [main] INFO reactor.Flux.Map.1 - onComplete()

第一个消息是从doOnNext的{​​{1}}写的,之后是合并的发布者的stringFlux,最后一个是log

P.S。您还可以记录其他事件,例如OnError,OnComplete等。