Java Reactive Programming — Flux Create vs Flux Generate

Overview:

  1. Reactive Programming — A Simple Introduction
  2. Reactive Programming — Creating Sequences — Flux vs Mono
  3. Reactive Programming — Publisher Types — Cold Vs Hot

Flux Create:

going to emit - 0
going to emit - 1
going to emit - 2
going to emit - 3
going to emit - 4
going to emit - 0
going to emit - 1
going to emit - 2
going to emit - 3
going to emit - 4
First :: 0
Second:: 0
First :: 1
First :: 2
Second:: 1
First :: 3
First :: 4
Second:: 2
Second:: 3
Second:: 4
  • Each observer gets its own FluxSink instance which is expected as we create a Cold publisher.
  • Create method does not wait for the observer to process the elements. It emits the elements even before observers start processing the elements.
First :: 0
Second:: 0
First :: 1
First :: 2
Second:: 1
First :: 3
First :: 4
Second:: 2
Second:: 3
Second:: 4
Runnable runnable = () -> {
IntStream.range(0, 5)
.forEach(fluxSinkConsumer::publishEvent);
};

for (int i = 0; i < 3; i++) {
new Thread(runnable).start();
}

Flux Generate:

  • In the above Consumer<FluxSink<Integer>> we have a loop which keeps on emitting elements
  • We could see only one ‘Flux create’ message
  • We could see 100 ‘going to emit’ statements
  • Then all the 100 ‘First consumed’ statements one by one
  • We could see 32 ‘Flux generate’ messages
  • We could see 23 ‘First consumed’ messages
  • Again a bunch of ‘Flux generate’ messages
  • Again a bunch of ‘First consumed’ messages
Flux generate
[ERROR] (main) Operator called default onErrorDropped - reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalStateException: More than one call to onNext
reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalStateException: More than one call to onNext
Caused by: java.lang.IllegalStateException: More than one call to onNext
Consumed ::A
Consumed ::B
Consumed ::C
Consumed ::D
Consumed ::E
Consumed ::F
Consumed ::G
Consumed ::H
Consumed ::I
Consumed ::J
Consumed ::K
Consumed ::L
Consumed ::M
Consumed ::N
Consumed ::O
Consumed ::P
Consumed ::Q
Consumed ::R
Consumed ::S
Consumed ::T
Consumed ::U
Consumed ::V
Consumed ::W
Consumed ::X
Consumed ::Y
Consumed ::Z

Summary — Create vs Generate:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vinoth Selvaraj

Principal Software Engineer — passionate about software architectural design, microservices.