Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Hands-On Reactive Programming with Reactor
Hands-On Reactive Programming with Reactor

Hands-On Reactive Programming with Reactor: Build reactive and scalable microservices using the Reactor framework

eBook
$24.99 $35.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Hands-On Reactive Programming with Reactor

The Publisher and Subscriber APIs in a Reactor

The previous chapter provided you with a brief introduction to the evolution of the reactive paradigm. In that chapter, we discussed how Reactive Streams enable us to perform reactive modeling in imperative languages, such as Java. We also discussed the key components in reactive—the publisher and subscriber. In this chapter, we will cover these two components in detail. Since Reactive Streams is a specification, it does not provide any implementations of the two components. It only lists the responsibilities of the individual components. It is left to implementation libraries, such as Reactor, to provide concrete implementations for the interfaces. Reactor also provides different methods for instantiating publisher and subscriber objects.

We will cover the following topics in this chapter:

  • Comparing streams to existing Java...

Technical requirements

Stream publisher

As we discussed in the previous chapter, the publisher is responsible for the generation of unbounded asynchronous events, and it pushes them to the associated subscribers. It is represented by the org.reactivestreams.Publisher interface, as follows:

public interface Publisher<T> {
    public void subscribe(Subscriber<? super T> s);
}

The interface provides a single subscribe method. The method is invoked by any party that is interested in listening to events published by the publisher. The interface is quite simple, and it can be used to publish any type of event, be it a UI event (like a mouse-click) or a data event.

Since the interface is simple, let's add an implementation for our custom FibonacciPublisher:

public class FibonacciPublisher implements Publisher<Integer> {
@Override
public void subscribe(Subscriber<? super Integer...

Stream subscriber

A subscriber is used to listen to events generated by a publisher. When a subscriber registers to a publisher, it receives events in the following order:

As a result, the subscriber has the following interface to handle all of these events:

public interface Subscriber<T> {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}

Let's cover each of these methods in detail, as follows:

  • onSubscribe(Subscription s): As soon as a publisher has received a subscriber, it generates a subscription event. The generated subscription event is then received in the specified method.
  • onNext (T): All data events generated by a publisher are received by the subscriber in the specified method. A publisher may or may not publish a data event before closing the stream.
  • onCompletion()...

Reactive Streams comparison

Before we jump into Reactor, let's compare the Streams model with some of the existing similar APIs, such as the java.util.Observable interface and the JMS API. We will try to determine the similarities and the key differences between the APIs.

The Observable interface

The java.util.Observable interface implements the Observer pattern, which can be co-related here. However, all similarities end here. If we look at the Observable interface, we have the following methods:

public class Observable {
void addObserver (Observer o);
void deleteObserver (Observer o);
void deleteObservers();
void notifyObservers();
void notifyObserver(int arg);
int countObservers();
boolean hasChanged();
}

Let...

The Flux API

Flux<T> is a general purpose reactive publisher. It represents a stream of asynchronous events with zero or more values, optionally terminated by either a completion signal or an error. It is important to note that a Flux emits the following three events:

  • Value refers to the values generated by the publisher
  • Completion refers to a normal termination of the stream
  • Error refers to an erroneous termination of the stream:

All of the preceding events are optional. This can lead to streams of the following types:

  • Infinite stream: A publisher generating only value events, and no terminal events (completion and error)
  • Infinite empty stream: A stream generating no value events and no terminating events
  • Finite stream: A publisher generating N finite values, followed by a terminal event
  • Empty stream: A publisher generating no value events, and only terminal events...

The Mono API

Now that we have covered the Flux API, let's look at Mono. It is capable of generating a maximum of one event. This is a specific use case for Flux, capable of handling one response model, such as data aggregation, HTTP request-response, service invocation response, and so on. It is important to note that a Mono emits the following three events:

  • Value refers to the single value generated by the publisher
  • Completion refers to a normal termination of the stream
  • Error refers to an erroneous termination of the stream

Since Mono is a subset of Flux, it supports a subset of Flux operators. Let's look at how to build a Mono.

Generating a Mono

The Mono<T> API supports stream generation from various...

Building subscribers to Flux and Mono

Reactor Flux and Mono provide a wide choice of subscribe methods. Reactive publishers raise four types of events, namely subscription, value, completion, and error. Individual functions can be registered for each of the events. We can also register a subscriber without listening to any kind of event. Let's look at all of the possible variants offered, as follows:

fibonacciGenerator.subscribe(); (1)

fibonacciGenerator.subscribe(t -> System.out.println("consuming " + t)); (2)

fibonacciGenerator.subscribe(t -> System.out.println("consuming " + t),
e -> e.printStackTrace() ); (3)

fibonacciGenerator.subscribe(t -> System.out.println("consuming " + t),
e -> e.printStackTrace(),
()-> System.out.println("Finished")); (4)

fibonacciGenerator.subscribe...

Summary

In this chapter, we provided a detailed discussion of the publisher and the subscriber interfaces of Reactive Streams. We attempted to implement these interfaces to illustrate that there are many non-explicit rules for them. These rules have been converted into the Reactive Streams TCK, against which all implementations should be validated. We also compared the publisher-subscriber pattern with the existing Observer and JMS patterns used in Java. Next, we took a detailed look at the Flux and Mono implementations available in Reactor. We looked at methods for creating them, and then subscribed to the generated streams.

In the next chapter, we will look at the operators that can be used to modify the generated streams.

Questions

  1. How can we validate Reactive Stream publisher and subscriber implementations?
  2. How is the Reactive Stream publisher-subscriber model different from the JMS API?
  3. How is the Reactive Stream publisher-subscriber model different from the Observer API?
  4. What is the difference between Flux and Mono?
  5. What is the difference between SynchronousSink and FluxSink?
  6. What are the different lifecycle hooks available in Reactor?

Further reading

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Use reactive APIs, Flux, and Mono to implement reactive extensions
  • Create concurrent applications without the complexity of Java's concurrent API
  • Understand techniques to implement event-driven and reactive applications

Description

Reactor is an implementation of the Java 9 Reactive Streams specification, an API for asynchronous data processing. This specification is based on a reactive programming paradigm, enabling developers to build enterprise-grade, robust applications with reduced complexity and in less time. Hands-On Reactive Programming with Reactor shows you how Reactor works, as well as how to use it to develop reactive applications in Java. The book begins with the fundamentals of Reactor and the role it plays in building effective applications. You will learn how to build fully non-blocking applications and will later be guided by the Publisher and Subscriber APIs. You will gain an understanding how to use two reactive composable APIs, Flux and Mono, which are used extensively to implement Reactive Extensions. All of these components are combined using various operations to build a complete solution. In addition to this, you will get to grips with the Flow API and understand backpressure in order to control overruns. You will also study the use of Spring WebFlux, an extension of the Reactor framework for building microservices. By the end of the book, you will have gained enough confidence to build reactive and scalable microservices.

Who is this book for?

If you’re looking to develop event- and data-driven applications easily with Reactor, this book is for you. Sound knowledge of Java fundamentals is necessary to understand the concepts covered in the book.

What you will learn

  • Explore benefits of the Reactive paradigm and the Reactive Streams API
  • Discover the impact of Flux and Mono implications in Reactor
  • Expand and repeat data in stream processing
  • Get to grips with various types of processors and choose the best one
  • Understand how to map errors to make corrections easier
  • Create robust tests using testing utilities offered by Reactor
  • Find the best way to schedule the execution of code

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 29, 2018
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781789135794
Category :
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 29, 2018
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781789135794
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 92.98
Hands-On Reactive Programming with Reactor
$43.99
Hands-On Reactive Programming in Spring 5
$48.99
Total $ 92.98 Stars icon

Table of Contents

12 Chapters
Getting Started with Reactive Streams Chevron down icon Chevron up icon
The Publisher and Subscriber APIs in a Reactor Chevron down icon Chevron up icon
Data and Stream Processing Chevron down icon Chevron up icon
Processors Chevron down icon Chevron up icon
SpringWebFlux for Microservices Chevron down icon Chevron up icon
Dynamic Rendering Chevron down icon Chevron up icon
Flow Control and Backpressure Chevron down icon Chevron up icon
Handling Errors Chevron down icon Chevron up icon
Execution Control Chevron down icon Chevron up icon
Testing and Debugging Chevron down icon Chevron up icon
Assessments Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(3 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Maxterm Feb 23, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Seems like the bloggers overtake the book space now...There are grammar & spelling mistakes everywhere, code is badly formatted.A lot of pages are almost empty, guess it looks better to have 250 pages, instead of 100.The content is superficial. It's more like an API "reference", if you're willing to call it that. It lacks explanation of concepts and just goes through various Classes and Interfaces briefly describing the usage with an example. I stopped at 70% of the book. You could compress the knowledge gained at that point into a few well written pages.Another annoyance are those frequent "let's try something. Uh this doesn't work, but we could fix it. But let's not bother and move on" examples that make up a chapter. I have no idea what the author thought of that.All in all I will contact Amazon for a Kindle refund. Don't bother, go read some blog posts about Reactor.From a book like this, you would expect some deep conceptual explanations that go beyond simple tutorials. The beauty of books usually lay in the fact that the author spend a tremedous amount of time sorting through the content and fine-tuning it's presentation to convey information in a very structured, meaningful way that usually far exceeds the quality of blog posts and online documentation...Not so here. This book actually manages to lower the bar compared to blog posts and online documentation. It is completely useless... Maybe if it was priced at 5$ it'd be worth a shot.Just Google for the free official documentation, "Reactor 3 Reference Guide", that is what you actually want.
Amazon Verified review Amazon
Amazon Customer Nov 06, 2022
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
If this book is intended for junior Java programmers, then they will stop reading after the IntelliJ project definition instructions. How to create a project using IntelliJ IDE the author explained not bad. How to use the Reactive paradigm and what is this paradigm about is not explained at all. Instead, the author overwrites ReactiveX online manuals. If this book is intended for Java experts, should they buy it? I have a doubt. The online manual provides not less information than the book. Personally, I expected for an added value.
Amazon Verified review Amazon
Amazon Customer Dec 02, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
A rewording of the online documentation
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.