The difference between the map and flatMap of reactor3 flux

  reactor

Order

This article mainly studies the difference between flux and flatMap.

map

    @Test
    public void testMap() throws InterruptedException {
        Flux.just(1, 2, 3, 4)
                .log()
                .map(i -> {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return i * 2;
                })
                .subscribe(e -> LOGGER.info("get:{}",e));
    }

Here the map of the header is a pure element transformation

Output

10:53:57.058 [main] INFO reactor.Flux.Array.1 - | onSubscribe([Synchronous Fuseable] FluxArray.ArraySubscription)
10:53:57.062 [main] INFO reactor.Flux.Array.1 - | request(unbounded)
10:53:57.063 [main] INFO reactor.Flux.Array.1 - | onNext(1)
10:53:58.067 [main] INFO com.example.demo.FluxTest - get:2
10:53:58.067 [main] INFO reactor.Flux.Array.1 - | onNext(2)
10:53:59.071 [main] INFO com.example.demo.FluxTest - get:4
10:53:59.071 [main] INFO reactor.Flux.Array.1 - | onNext(3)
10:54:00.076 [main] INFO com.example.demo.FluxTest - get:6
10:54:00.076 [main] INFO reactor.Flux.Array.1 - | onNext(4)
10:54:01.080 [main] INFO com.example.demo.FluxTest - get:8
10:54:01.081 [main] INFO reactor.Flux.Array.1 - | onComplete()

flatMap

    @Test
    public void testFaltMap() throws InterruptedException {
        Flux.just(1,2,3,4)
                .log()
                .flatMap(e -> {
                    return Flux.just(e*2).delayElements(Duration.ofSeconds(1));
                })
                .subscribe(e -> LOGGER.info("get:{}",e));
        TimeUnit.SECONDS.sleep(10);
    }

FlatMap here converts elements into Mono or Flux, and asynchronous operations can also be performed in the conversion operation.

Output

10:54:01.088 [main] INFO reactor.Flux.Array.2 - | onSubscribe([Synchronous Fuseable] FluxArray.ArraySubscription)
10:54:01.089 [main] INFO reactor.Flux.Array.2 - | request(256)
10:54:01.089 [main] INFO reactor.Flux.Array.2 - | onNext(1)
10:54:01.137 [main] INFO reactor.Flux.Array.2 - | onNext(2)
10:54:01.137 [main] INFO reactor.Flux.Array.2 - | onNext(3)
10:54:01.138 [main] INFO reactor.Flux.Array.2 - | onNext(4)
10:54:01.138 [main] INFO reactor.Flux.Array.2 - | onComplete()
10:54:02.143 [parallel-1] INFO com.example.demo.FluxTest - get:2
10:54:02.143 [parallel-1] INFO com.example.demo.FluxTest - get:4
10:54:02.143 [parallel-1] INFO com.example.demo.FluxTest - get:6
10:54:02.143 [parallel-1] INFO com.example.demo.FluxTest - get:8

Summary

FlatMap’s transformation Function requires the return of a Publisher that represents an asynchronous transformation operation on an element. Map is only a synchronous element conversion operation.

doc