reactor

Reactor use doOnNext multiple times


I was trying to change a little reactor samples from here and I'm a little confused with the behaviour I get.

So first I code like this:

    EmitterProcessor<String> stream = EmitterProcessor.<String>create().connect();
    Flux<String> flux = stream
            .doOnNext(s -> System.out.println("1 " + s))
            .doOnNext(s -> System.out.println("2 " + s));
    flux.subscribe();
    stream.onNext("Hello");

This code prints two lines as expected:

1 Hello
2 Hello

But if I add an intermediate varaible pretending I get it from some method or for readability the code starts to behave differently.

    EmitterProcessor<String> stream = EmitterProcessor.<String>create().connect();
    Flux<String> flux = stream
            .doOnNext(s -> System.out.println("1 " + s));
    flux .doOnNext(s -> System.out.println("2 " + s));
    flux.subscribe();
    stream.onNext("Hello");

So for the code above I get only one line, that is:

1 Hello

Can anybody explain this behaviour?


Solution

  • Thanks to Stephane Maldini I realised that Flux is immutable and each operation produces different flows. Discussion is here