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
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
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 : 9781789136340
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Sep 29, 2018
Length: 250 pages
Edition : 1st
Language : English
ISBN-13 : 9781789136340
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 69.98
Hands-On Reactive Programming with Reactor
€32.99
Hands-On Reactive Programming in Spring 5
€36.99
Total 69.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.