Reactor Basics with example | Create, Subscribe, Synchronous, Async, Parallel, Backpressure, Non-Blocking | Good for beginners

In this article we will go through very basic & simple examples of Project Reactor (by Pivotal) to understand different ways in which publisher & subscriber interact to perform desired operations.

Here is the Maven dependency for io.projectreactor – reactor-core

Reactor Synchronous

This is example where publishing & subscribing is synchronous. Publisher & subscriber both run on same thread.

  • create() – Creates Flux i.e. publisher i.e. emitter.
  • subscribe() – Subscribes to Flux i.e. publisher i.e. emitter & starts receiving emitted values.



Subscriber takes 100ms to complete processing. You can see that, when subscriber takes 100 ms to process, publisher is blocked during that time. Next value will be published only when subscriber processing is finished.



Reactor Asynchronous

In this example, we will put publisher i.e. Flux & subscriber on different threads & make it asynchronous.

  • create() – Creates Flux i.e. publisher i.e. emitter.
  • subscribeOn() – Informs Flux to put subscriber in different thread that current thread i.e. main thread.
  • publishOn() – Informs Flux to put publisher i.e. Flux in different thread that current thread i.e. main thread.
  • subscribe() – Subscribes to Flux i.e. publisher i.e. emitter & starts receiving emitted values.

You can see in output that thread names for publisher & subscriber are different. Also publisher is not waiting for subscriber to finish processing.



Reactor Parallel processing

If there is some processing that needs to be done on large emitted data set, then processing can be put on parallel operation & then after completion, it can be merged back as shown in below example.

  • create() – Creates Flux i.e. publisher i.e. emitter.
  • parallel() & runOn() –  Converts Flux to ParallelFlux & Informs it to put further processing in different thread that current thread i.e. main thread.
  • map() – This does the processing of calculating squares of all numbers & map it to ParallelFlux.
  • sequential() – Merges parallel operation results & converts ParallelFlux back to Flux.
  • subscribe() – Subscribes to Flux & starts receiving emitted values.



Leave a Reply

Your email address will not be published.