聊聊Flux的compose与flatMap操作

codecraft

本文主要研究下Flux的compose与flatMap操作

compose

        Flux.just("1", "2","3")
                .log()
                .compose(stringFlux -> {
                    LOGGER.info("compose executed");
                    return stringFlux.map(e -> e + "$");
                }).subscribe(LOGGER::info);

输出如下:

20:59:15.692 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
20:59:15.702 [main] INFO com.example.demo.FluxTest - compose executed
20:59:15.707 [main] INFO reactor.Flux.Array.1 - | onSubscribe([Synchronous Fuseable] FluxArray.ArraySubscription)
20:59:15.709 [main] INFO reactor.Flux.Array.1 - | request(unbounded)
20:59:15.709 [main] INFO reactor.Flux.Array.1 - | onNext(1)
20:59:15.709 [main] INFO com.example.demo.FluxTest - 1$
20:59:15.710 [main] INFO reactor.Flux.Array.1 - | onNext(2)
20:59:15.710 [main] INFO com.example.demo.FluxTest - 2$
20:59:15.710 [main] INFO reactor.Flux.Array.1 - | onNext(3)
20:59:15.710 [main] INFO com.example.demo.FluxTest - 3$
20:59:15.710 [main] INFO reactor.Flux.Array.1 - | onComplete()
可以看到compose executed只打印一次

flatMap

        Flux.just("1","2","3")
                .log()
                .flatMap(s -> {
                    LOGGER.info("flatMap executed");
                    return Flux.just(s+"$");
                }).subscribe(LOGGER::info);

输出如下:

21:00:54.497 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
21:00:54.516 [main] INFO reactor.Flux.Array.1 - | onSubscribe([Synchronous Fuseable] FluxArray.ArraySubscription)
21:00:54.519 [main] INFO reactor.Flux.Array.1 - | request(256)
21:00:54.520 [main] INFO reactor.Flux.Array.1 - | onNext(1)
21:00:54.520 [main] INFO com.example.demo.FluxTest - flatMap executed
21:00:54.520 [main] INFO com.example.demo.FluxTest - 1$
21:00:54.520 [main] INFO reactor.Flux.Array.1 - | onNext(2)
21:00:54.520 [main] INFO com.example.demo.FluxTest - flatMap executed
21:00:54.520 [main] INFO com.example.demo.FluxTest - 2$
21:00:54.520 [main] INFO reactor.Flux.Array.1 - | onNext(3)
21:00:54.520 [main] INFO com.example.demo.FluxTest - flatMap executed
21:00:54.520 [main] INFO com.example.demo.FluxTest - 3$
21:00:54.521 [main] INFO reactor.Flux.Array.1 - | onComplete()
可以看到flatMap executed在每次onNext的时候都打印一次

小结

compose操作是将整个flux作为一个整体输入一次性转换,而flatMap是针对flux的每个item作为输入来进行转换。

doc

阅读 1.9k

code-craft
spring boot , docker and so on 欢迎关注微信公众号: geek_luandun

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.6k 声望
1.9k 粉丝
0 条评论
你知道吗?

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.6k 声望
1.9k 粉丝
文章目录
宣传栏