Why can't I use concatWith after Flux initiation

Viewed 128

I'm newbie and I'm learning Spring Flux. I couldn't understand the Following: Watermelon is being printed here:

Flux<String> fruitFlux = Flux.just("Apple", "Banana", "Orange").concatWith(Flux.just("Watermelon"));
fruitFlux.subscribe( System.out::println);

But when using the following code, it doesn't get printed:

Flux<String> fruitFlux = Flux.just("Apple", "Banana", "Orange");
fruitFlux.concatWith(Flux.just("Watermelon"));
fruitFlux.subscribe( System.out::println);

Shouldn't those two code blocks be exactly the same?

1 Answers

No - Flux is immutable, and operators like concatWith return a new instance of the Flux modified accordingly. They don't mutate the original publisher.

In your second example, you're ignoring that new instance, so it'll have no effect.

If you did fruitFlux = fruitFlux.concatWith(Flux.just("Watermelon")); instead, then you'd see the result you expected.

Related