Search code examples
javareactive-programmingspring-webfluxproject-reactor

Project Reactor : how the threads will create in case of subscription and publishedOn, how the flow goes?, Stack trace?


simple example to understand the thread flow.

  1. [gshp subscribedOn-1] INFO reactor.Flux.FlatMap.1 -onSubscribe(FluxFlatMap.FlatMapMain)

  2. [gshp publishOn-7] INFO reactor.Flux.FlatMap.1 - onNext(6)

Here reactor.Flux.FlatMap.1 is common for both gshp subscribedOn-1, gshp publishOn-7

When we run java, it starts with main thread after that what happens, will it creating gshp subscribedOn-1 or reactor.Flux.FlatMap.1?

  @Test
  public void setUpTestTest() {
      Scheduler scheduler1 = Schedulers.newParallel("gshp subscribedOn", 3);
      Scheduler scheduler2 = Schedulers.newParallel("gshp publishOn", 6);
      Flux<String> flux = Flux.range(1, 200)
                              .flatMap(s-> Flux.just(""+s)
                                               .publishOn(scheduler2)
                                               .concatMap(d->processMessagefluxpause(d, "test")))
                                               .log()
                              .subscribeOn(scheduler1);

    StepVerifier.create(flux).expectNextCount(20).verifyComplete();
}

What it means, how the flow goes? enter image description here


Solution

  • here you can read about subscribeOn and publishOn.

    publishOn vs subscribeOn

    basically as soon as someone subscribes, the entire chain is created and the call is assigned a thread. If you have anywhere a subscribeOn in the chain the entire call will use this scheduler. So it doesn't matter where subscribeOnis placed.

    You can see that in the logs, its starts out, with the call getting placed on the subscribeOn scheduler.

    the publishOn on the other hand, as soon as we reach that statement, the thread switches to that scheduler mid way. So this is more dependant on where in the chain it is placed.

    Your logs show that when the inner Flux is emitting it is emitting on the publishOn scheduler.