gpt4 book ai didi

java - Reactor compose 与 flatMap

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:20 24 4
gpt4 key购买 nike

我继续玩 Reactor,现在我看到 compose 运算符的行为与 flatMap 完全一样,我想知道是否有任何我不知道的区别明白了。

    @Test
public void compose() throws InterruptedException {
Scheduler mainThread = Schedulers.single();
Flux.just(("old element"))
.compose(element ->
Flux.just("new element in new thread")
.subscribeOn(mainThread)
.doOnNext(value -> System.out.println("Thread:" + Thread.currentThread().getName())))
.doOnNext(value -> System.out.println("Thread:" + Thread.currentThread().getName()))
.subscribe(System.out::println);
Thread.sleep(1000);
}

@Test
public void flatMapVsCompose() throws InterruptedException {
Scheduler mainThread = Schedulers.single();
Flux.just(("old element"))
.flatMap(element ->
Flux.just("new element in new thread")
.subscribeOn(mainThread)
.doOnNext(value -> System.out.println("Thread:" + Thread.currentThread().getName())))
.doOnNext(value -> System.out.println("Thread:" + Thread.currentThread().getName()))
.subscribe(System.out::println);
Thread.sleep(1000);
}

这两个示例的行为和返回相同的结果。

问候。

最佳答案

@Andrew 的解释非常好。只是想添加一个示例以便更好地理解。

Flux.just("1", "2")
.compose( stringFlux -> {
System.out.println("In compose"); // It takes whe whole Flux as input
return stringFlux.collectList();
}).subscribe(System.out::println);


Flux.just("1", "2").flatMap(s -> { //Input to the anonymous function is individual items in stream
System.out.println("In flatMap");
return Flux.just(Integer.parseInt(s));
}).subscribe(System.out::println);

这会产生输出

In compose
[1, 2]
In flatMap
1
In flatMap
2

这表明 compose 适用于整个流,但 flatMap 适用于流中的单个项目

关于java - Reactor compose 与 flatMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com