Search code examples
springreactive-programmingspring-webflux

At what point does the subscription take place? (spring webflux)


At what point does the spring webflux do the subscription? Everywhere I have read that there must be a subscription otherwise no change happens. In my short time with Spring Webflux, I have never seen a subscribe() neither in the controller or services.

My doubt is also when using flatMap(), map(),... etc.. at what point does the subscription take place?

What I have read does not really resolve my doubts.

public Flux method(){
    ....
    myFlux.flatMap(data -> {
          ....

    }).flatMap(e -> { .... });
}

I know this is an asynchronous issue, but each flatMap runs at the same time?...and so sometimes some data I have noticed is null.


Solution

  • It's the framework (spring-webflux) that subscribes to the returned Mono or Flux. For example if you use Netty (that's the default), then subscription happens here based on my debugging: https://github.com/reactor/reactor-netty/blob/db27625064fc78f8374c1ef0af3160ec3ae979f4/reactor-netty-http/src/main/java/reactor/netty/http/server/HttpServer.java#L962

    Also, this article might be of help to understand what happens when: https://spring.io/blog/2019/03/06/flight-of-the-flux-1-assembly-vs-subscription