Talk about Flux’s compose and flatMap operations

  reactor

Order

This paper mainly studies the composition and flatMap operations of Flux.

compose

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

The output is as follows:

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()

You can see that compose executed only prints once.

flatMap

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

The output is as follows:

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()

You can see that flatMap executed prints once every time onNext.

Summary

The compose operation is to convert the entire flux as a whole input at one time, while flatMap is to convert each item of flux as an input.

doc