Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Scala Reactive Programming
Scala Reactive Programming

Scala Reactive Programming: Build scalable, functional reactive microservices with Akka, Play, and Lagom

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Scala Reactive Programming

Getting Started with Reactive and Functional Programming

In recent times, the word Reactive has gained popularity far and wide. We can see this word in all IT books, magazines, blogs, tutorials, videos on YouTube, and so on.

Almost all programming languages, tools, IDEs, and platforms already support the Reactive architecture and the rest will move to it soon.

Here are some terms that are commonly heard in the Reactive world:

  • Reactive, Reactiveness, Reactive Manifesto, and Reactive Streams
  • Reactive programming (RP), Function Reactive Programming (FRP), OOP RP, Imperative RP, and Reactive Engine
  • Reactive system, Reactive applications, Reactive microservices, and Reactive Web Applications
  • Reactive Architecture, Reactive Design Patterns, and Reactive principles
  • Reactive tools, Reactive Platform, and Lightbend Reactive Platform
  • Reactive Extensions (Rx)—Rx Scala, Rx Java, Scala, Akka, Play Framework
  • Java Reactive API and Spring Reactor project

Are you really curious to know what Reactive is? Do you have the following questions and more in your mind—What is Reactive programming? Why do we need it? How do we write RP? Why is FP good for RP? What are the benefits of RP?

If yes, this book is for you. I'll introduce you to the Reactive World in a simple and easy way. I like a Diagram/Example-driven approach to learn new concepts and I feel you will like it too.

We can develop Reactive applications using a wide variety of languages or technologies. However, we will use Lightbend Reactive Platform in this book to develop our Reactive microservices.

Welcome to the Reactive World! Let's understand the Reactive World now. In this chapter, we will discuss the following topics:

  • What is Reactive? What is RP and FRP? What are the benefits of RP?
  • What is the Reactive Manifesto and what are its main goals?
  • Why is FP the best fit for RP?
  • What is the Java Reactive Streams API?
  • A discussion on the Flow API
  • What are Reactive Extensions?
  • What is the difference between Reactive and Observer Design Patterns?
  • What are RP Operators?
  • Marble diagrams for RP Operators

Introduction to Reactive

Before diving into the Reactive Manifesto, Reactive Streams Specification, or Java 9 Flow API, and Functional Reactive Programming (FRP), we will first understand the meaning of Reactive and Reactive programming in this section.

What is Reactive?

Reactive means reacting to changes in a timely manner or responding to changes in a timely manner.

Here, in the Reactive World, we can represent a change as an event. So we can also define Reactive as reacting to events in a timely manner. This change can occur on data or data elements.

Whenever a change occurs in our system, the system should react to those changes immediately in a timely manner. In the current world, users expect a response from an application (website, web application, mobile application, and so on) quickly and in a timely manner. If the system or application does not respond to the user (or customer) in a timely manner, the user will look for some other option and our application will lose its users.

In the Merriam Webster dictionary, Reactive means being readily responsive to a stimulus (check out https://www.merriam-webster.com/dictionary/Reactive).

In the Reactive World, a change is an event. In Reactive systems, we represent that event as a message. We will discuss why we need to represent an event as a message in detail in subsequent sections.

What is Reactive programming?

Unlike imperative programming (IP) or (Object-Oriented Programming) OOP, where we write our code in terms of the order of lines or statements, in Reactive programming (RP), we write the code or programs in terms of events.

In simpler words, RP means writing programs using events, or RP means writing programs that define how to react to events. As we discussed, events are changes in the state of the program or application. So we can also define RP as follows:

Reactive programming is a kind of programming paradigm to that propagates changes.

Let's discuss one of the important and frequently used RP examples (almost all books or tutorials use the same scenario). Consider the following example of a spreadsheet application:

Observe that the A3 cell has a formula =A1+A2, that is, A3 is the sum of the values of the cells A1 and A2.

Initially, A3 has a value of 0. When we change the value of cell A1 or A2, or both, the spreadsheet updates the value of A3:

We can observe that the cell A3 is updated with 3 automatically; this is Reactive programming.

What is a data stream or stream?

In Reactive programming, we write programs to work on a sequence of events. For instance, in a spreadsheet, we can observe the following events in a sequence:

  1. The user enters a value 1 into cell A1. When the user inputs data into cell A1, the value in cell A3 is updated to 1.
  2. The user enters a value 2 into cell A2. When the user inputs data to cell A2, A3 is updated to 3.

In the Reactive World, this sequence of events happening over time is known as a stream, events stream, or data stream. The following diagram shows how a sequence of events forms an events stream. It also shows how a Publisher sends events to an event stream and how a Subscriber receives events from that event stream:

A stream or data stream is a sequence of ongoing events ordered in time.

In RP, the Publisher sends events to a Stream, and the Subscriber consumes those events from the Stream.

To react to events, we should monitor them. In RP, the process of monitoring events is known as listening to events or subscribing to events.

We can also define RP using this data stream:

RP is a programming paradigm to do programming with asynchronous data streams.

Event stream = A sequence of events

RP versus Reactive systems versus Reactive architecture

A Reactive system is a set of components that communicate with each other reactively. By combining those individual components into one, we can form a modern distributed system. We can develop a Reactive system by following a set of architectural design principles.

Reactive system components work as a single system and they react to changes in a timely manner.

Reactive systems or Reactive applications have the following features:

  • Responsiveness: They react to users in a timely manner
  • Elasticity: They react to load
  • Resilience: They react to failures
  • Message-Driven: They react to events or messages

We will discuss these components of Reactive Streams in detail in the Reactive Manifesto section. Reactive Architecture is a technique or a process of designing Reactive systems.

We can develop Reactive systems using many techniques. However, RP or FRP are the best tools to build Reactive systems.

The core principle of a Reactive system is developing its components using a Message-Driven approach, whereas RP is all about writing programs using events, which means it follows an Event-Driven approach.

As we said, a Reactive system is a set of components. We use RP at the component level, which means that we develop each component using RP. We use a Reactive system at the system level.

Event-Driven versus Message-Driven

The core principle of RP is the Event-Driven approach, whereas the core principle of a Reactive system is the Message-Driven approach.

RP gives us the benefits at component level only because events are emitted and processed locally. They cannot work across the network in a distributed system.

Reactive systems give us the benefits at the system level, because messages are processed and communicated across the network in a distributed system.

We cannot get the full benefits just with RP; we should use the combination of RP and the Reactive system.

In a Reactive system with RP, generated events are represented as messages under-the-hood, and they are processed as messages.

Benefits of Reactive systems with RP

We will get more benefits when we use RP as a programming paradigm to develop the components of a Reactive system. The combination of RP and Reactive systems gives us the following benefits:

  • Self-healing: As per the Reactive Streams specification, RP should support Resilience. This means we can write Reactive systems in a way that they have some technique to recover from failure and continue working to give responses to the clients. This is known as self-healing. A client will not know about this, and they will never see those failures.
  • Highly available systems: As per the Reactive Streams specification, RP should support Elasticity (scale up/down and scale out/in). This means we can write Reactive systems in a way that they are always available. They support 100% up time.
  • Highly Scalable to support heavy loads.
  • Loose coupling.
  • Utilizes system resources (both hardware and software) efficiently.
  • Provides better responsiveness.
  • Provides real-time behavior or data streaming.
  • Easy to perform distributed data processing.
  • Supports Location Transparency.
  • Low latency.
  • Better performance.
  • Ease of maintainability.
  • No need to use anonymous callbacks (so no more callback hell).
  • Easy to address and handle failures.
  • Easy to reason about failures.

We should also understand the things that are forcing us to develop and use Reactive systems:

  • IoT (Internet of Things)
  • Cloud environment or services
  • Big data systems
  • Real-time fast data streaming
  • Mobile architectures
  • Communication between heterogeneous systems
  • Multicore hardware architecture
Here, Reactive systems means Reactive Web Applications, Reactive applications, and Reactive microservices. In my point of view, all have the same meaning.

So far, we have discussed Reactive World, that is, RP. Now, it's time to enter the Functional World, that is, functional programming.

Functional programming

So far, we have discussed RP. Now it's time to move to FP (Functional Programming). Before discussing FRP, we should understand what FP is. We will discuss what FP is, its principles, and its benefits in this section.

What is functional programming?

Like OOP (Object-Oriented Programming), FP is a kind of programming paradigm.

It is a programming style in which we write programs in terms of pure functions and immutable data. It treats its programs as function evaluation.

As we use pure functions and immutable data to write our applications, we will get lots of benefits for free. For instance, with immutable data, we do not need to worry about shared-mutable states, side effects, and thread-safety.

It follows a Declarative programming style, which means programming is done in terms of expressions, not statements.

For instance, in OOP or imperative programming paradigms, we use statements to write programs where FP uses everything as expressions.

Principles of functional programming

FP has the following principles:

  • Pure functions
  • Immutable data
  • No side effects
  • Referential transparency (RT)
  • Functions are first-class citizens
  • Functions that include anonymous functions, higher order functions, combinators, partial functions, partially-applied functions, function currying, closures
  • Tail recursion
  • Functions composability

We will discuss these principles or properties of FP in brief here because we have a dedicated chapter on these concepts. Refer to Chapter 2, Functional Scala, to understand these concepts in-depth with some simple examples.

A pure function is a function that always returns the same results for the same inputs irrespective of how many times and where you run this function.

We will get lots of benefits with immutable data. For instance, no shared data, no side effects, thread safety for free, and so on.

Like an object is a first-class citizen in OOP, in FP, a function is a first-class citizen. This means that we can use a function as any of these:

  • An object
  • A value
  • A data
  • A data type
  • An operation

In simple words, in FP, we treat both functions and data as the same.

We can compose functions that are in sequential order so that we can solve even complex problems easily. Higher-Order Functions (HOF) are functions that take one or more functions as their parameters or return a function as their result or do both.

For instance, map(), flatMap(), filter(), and so on are some of the important and frequently used higher-order functions. Consider the following example:

map(x => x*x) 

Here, the map() function is an example of Higher-Order Function because it takes an anonymous function as its parameter. This anonymous function x => x *x is of type Int => Int, which takes an Int as input and returns Int as its result.

An anonymous function is a function without any name.

Refer to Chapter 2, Functional Scala, to understand these concepts very well. I have provided a useful description and also some simple and easy-to-understand examples.

Benefits of functional programming

FP provides us with many benefits:

  • Thread-safe code
  • Easy-to-write concurrency and parallel code
  • We can write simple, readable, and elegant code
  • Type safety
  • Composability
  • Supports Declarative programming

As we use pure functions and immutability in FP, we will get thread-safety for free.

One of the greatest benefits of FP is function composability. We can compose multiple functions one by one and execute them either sequentially or parentally. It gives us a great approach to solve complex problems easily.

Functional Reactive programming

The combination of FP and RP is known as function Reactive programming or, for short, FRP. It is a multiparadigm and combines the benefits and best features of two of the most popular programming paradigms, which are, FP and RP.

FRP is a new programming paradigm or a new style of programming that uses the RP paradigm to support asynchronous non-blocking data streaming with backpressure and also uses the FP paradigm to utilize its features (such as pure functions, immutability, no side effects, RT, and more) and its HOF or combinators (such as map, flatMap, filter, reduce, fold, and zip).

Refer to Chapter 7, Working with Reactive Streams, to know more about backpressure.

In simple words, FRP is a new programming paradigm to support RP using FP features and its building blocks.

FRP = FP + RP, as shown here:

Today, we have many FRP solutions, frameworks, tools, or technologies. Here's a list of a few FRP technologies:

  • Scala, Play Framework, and Akka Toolkit
  • RxJS
  • Reactive-banana
  • Reactive
  • Sodium
  • Haskell

This book is dedicated toward discussing Lightbend's FRP technology stack—Lagom Framework, Scala, Play Framework, and Akka Toolkit (Akka Streams).

FRP technologies are mainly useful in developing interactive programs, such as rich GUI (graphical user interfaces), animations, multiplayer games, computer music, or robot controllers.

Types of RP

Even though most of the projects or companies use FP Paradigm to develop their Reactive systems or solutions, there are a couple of ways to use RP. They are known as types of RP:

  • FRP (Functional Reactive Programming)
  • OORP (Object-Oriented Reactive Programming)

However, FP is the best programming paradigm to conflate with RP. We will get all the benefits of FP for free.

Why FP is the best fit for RP

When we conflate RP with FP, we will get the following benefits:

  • Composability—we can compose multiple data streams using functional operations so that we can solve even complex problems easily
  • Thread safety
  • Readability
  • Simple, concise, clear, and easy-to-understand code
  • Easy-to-write asynchronous, concurrent, and parallel code
  • Supports very flexible and easy-to-use operations
  • Supports Declarative programming
  • Easy to write, more Scalable, highly available, and robust code

In FP, we concentrate on what to do to fulfill a job, whereas in other programming paradigms, such as OOP or imperative programming (IP), we concentrate on how to do.

Declarative programming gives us the following benefits:

  • No side effects
  • Enforces to use immutability
  • Easy to write concise and understandable code

The main property of RP is real-time data streaming, and the main property of FP is composability. If we combine these two paradigms, we will get more benefits and can develop better solutions easily.

In RP, everything is a stream, while everything is a function in FP. We can use these functions to perform operations on data streams.

Reactive Manifesto

Reactive Manifesto is a manifesto that describes how to design and architect Reactive systems according to your needs. It describes the four traits of Reactive systems. As of now, we are using Reactive Manifest v.2.0, which was initially published on September 16, 2014.

As per Reactive Manifest 1.0 (initial and old version), Reactive systems are Responsive, Scalable, Resilient, and Event-Driven.

As per Reactive Manifest 2.0, Reactive systems are Responsive, Scalable, Resilient, and Message-Driven.

We can find the manifesto on GitHub as a repository, available at https://github.com/reactivemanifesto/reactivemanifesto.

Need of Reactive Manifesto

We need to understand what the main need of Reactive Manifesto is, so that we will get clear picture about it.

The main needs or goals of Reactive Manifesto are as follows:

  • Users or customers need responses in a timely manner. They don't like slow responses and they don't use slow systems. If they don't get quick responses as needed, they will look for other options.
  • We should have an API to support asynchronous streaming data with non-blocking backpressure.
  • API for Reactive Technology (frameworks, tools, languages, IDEs, and so on) implementors.
  • Heterogeneous Reactive systems should work in an interoperable way.
  • We should have a better approach for consumers to avoid buffer overflow issues.

Principles of Reactive systems

In this section, we will discuss what the four traits or principles of Reactive systems are that we should follow to develop Reliable, Flexible, Scalable, Distributable, and Resilient applications.

Reactive Manifesto defines the following four principles:

  • Message-Driven
  • Elastic
  • Resilient
  • Responsive

This preceding diagram is copied from Reactive Manifesto. These are design and architectural principles. They are also known as the Four tenants of Reactive Streams or Four core building blocks of Reactive Streams.

We will pick up each trait one-by-one and discuss it in detail in subsequent sections.

Message-Driven

The core or base principle of the Reactive systems is Message-Driven architecture. It is the foundation principle or method for the rest of the three principles—Elasticity, Resilience, and Responsiveness.

This means a Reactive system depends on asynchronous message-passing between its components to use the benefits of Message-Driven architecture for free.

In simple words, Message-Driven = React to messages.

Even though RP represents the system's changes in terms of events, a Reactive system converts them into messages under the hood.

One more important point to note is that in a Reactive system, even failures are represented as messages, so it's easy to perform failure handling.

So, in a Reactive system, all of its components communicate with each other by sending messages. The Message-Driven approach gives us the following benefits:

  • Messages are immutable by design
  • They share nothing, so are thread-safe by design
  • They provide loose coupling between system components
  • They can work across the network, so they support Location Transparency
  • They support scalability
  • They support Resilience because they avoid single-point-of-failure using partitioning and replication techniques
  • They support better throughput
  • They provide easy-to-apply backpressure

So in RP, we write code in a stream of events, and then Reactive systems convert them into a stream of messages.

Elasticity

Elasticity means scalability. Our system should support scale up/scale down and scale out/ scale in. Our Reactive system should support scale up/scale out so that it responds to the users in a timely manner. It should also support scale down/scale in order to save our organization cost.

In simple words, Elastic = React to load.

This means our system should respond to users in a timely manner even at a heavy load.

With this property, a Reactive system can allocate and/or deallocate resources for every component dynamically and automatically to match demands.

If our Reactive system follows the Message-Driven approach, it supports Elasticity easily:

Elasticity = Scale up/down + Scaleout/in

Scale up: When the load increases, a Reactive system should be able to easily upgrade it with more and more powerful resources (for instance, more CPU Cores) automatically, based on the demand:

Scale down: When the load decreases, a Reactive system should be able to easily degrade it by removing some resources (for instance, CPU Cores) automatically, based on demand:

Scale out: When the load increases, a Reactive system should be able to easily extend it by adding some new nodes or servers automatically, based on the demand:

Scale in: When the load decreases, a Reactive system should be able to easily sink it by removing some nodes or servers automatically, based on the demand:

Resilience

Resilience is not just fault-tolerance, it's beyond fault-tolerance. A Reactive system should fully recover from failure; this is known as self-healing.

In simple words, Resilient = React to failure.

Resilience means a Reactive system should respond to users even in the event of failures, by recovering itself. This is possible by isolating the failure handling to a different component. In a Reactive system, all failures are converted into messages and then processed.

For instance, in Akka Toolkit, Akka Streams (one of the popular Reactive Streams implementations) uses the supervision technique to do this failure handling.

Refer to Chapter 4, Building Reactive Applications with Akka, to understand this Supervision technique.

In a Reactive system:
  • Failures are messages
  • Events are messages

Responsiveness

The last but very important trait is responsiveness. In Reactive systems, Responsive means reacting to the users or customers in a timely manner. Here, we should understand this point—a user should get a response when needed, otherwise they will lose interest and go for other options. In the current Reactive World, the following two things are the same:

  • Not giving response to users when needed or in a timely manner
  • Not giving any response to users at all

Even though our system does give a response to the user at a later time, the user does not need it then. Our system loses the users and ultimately, we lose our business.

In simple words, Responsive = React to users.

After going through these four traits of a Reactive system, we should understand the following things:

  • The main goal of a Reactive system is responsiveness
  • The core method that a Reactive system should follow is Message-Driven
  • The core principles of a Reactive system are Elasticity and Resilience:

The core method of a Reactive system, that is, the Message-Driven approach, will give us Elasticity and Resilience for free:

These three traits of a Reactive system (that is, Message-Driven, Elasticity, and Resilience) give us the main goal or value of that Reactive system—responsiveness.

After going through the Reactive Manifesto, we can represent it in a pictorial form, as shown here:

Why Reactive Streams specification?

In this section, we will understand, first of all, why we really need the Reactive Streams specification. We will also answer a few more questions, like—What is the use of this specification or standard, and who really needs this specification?

RSS (Reactive Streams Specification) is a standard or specification. It explains how to develop frameworks, tools, toolkits, languages, libraries, IDEs, data stores, servers, and so on, which work in Reactive.

Are we getting any benefits by following this specification? Yes. That's why we need this specification.

The main goals or benefits of this specification are as follows:

  • To support reactiveness
  • To support interoperability:

If we observe the preceding diagram, we can understand that many applications are using many Reactive technologies. If they follow their own approach to develop their Reactive systems, then it is a bit tough for them to talk to or work with each other. It is possible to implement some kind of adapters or interfaces to fill the gap and make them work with each other. However, it is not only an old and tedious approach, but also outdated and obsolete.

If we have a specification or standard or API similar to the Reactive Streams Specification and everybody develops their tools, frameworks, and so on, by following this, then there will be no need for extra tools, such as adapters. They can work with each other without using any adapters and without any issues.

This means it enables heterogeneous Reactive systems to work with each other, that is, work in an interoperable way.

As a Java or Scala developer, we know what the use of an API is, why we need it, and who needs it. So, we need a Reactive API or standard or specification to implement or develop Reactive libraries, Reactive servers, Reactive languages, Reactive databases, Reactive tools, Reactive applications, or systems.

Initially, a set of developers from top companies such as Lightbend, Netflix, Pivotal, Redhot, and Oracle Corporation worked together on this area and prepared a specification to develop Reactive systems (or applications) easily. This is known as RSS (Reactive Streams Specification). They requested Oracle Corporation introduce an API to develop Reactive systems easily in a way that they should work interoperably. Finally, Oracle Corporation introduced a Reactive Streams API as part of JEP-266 in JDK 9 (Java SE 9). This API is known as the Flow API.

In the next section, we will discuss this Flow API in detail.

From my point of view, specification, standard, API, interface, abstract, and blue-print are all the same. They have the same meaning.

Why is Play Framework the best for Reactive systems?

Play Framework is the best full-stack web framework available in the current market to develop Reactive Web Applications, Reactive systems, Reactive architecture, Reactive microservices, or Reactive libraries using both FP and RP paradigms, that is, FRP.

The following are the reasons to clarify why Play is good for RP:

  • Play Framework is built on top of the Akka Toolkit
  • By design, the Akka Toolkit supports Reactive Architecture using an Actor Model and Akka Streams
  • Akka Streams is the best Reactive API to develop Reactive data streaming
  • Play Framework has an integrated module for the Akka Streams API
  • Play Framework is written in Scala (a JVM language) and supports both Scala and Java programming languages
  • Both Scala and Java run on JVM
  • Scala supports FP very well
  • FP is the best programming paradigm for RP
  • The latest Play Framework has moved from Iteratees to Reactive Streams
  • It is a full-stack web framework for Reactive programming

Reactive systems versus traditional systems

In this section, we will see the main differences between a Reactive system and non-Reactive system, that is, a traditional system.

The first and foremost difference is that a Reactive system takes a user or customer request as an event or message, and then reacts to those events in a timely manner. Once it's done, it continuously looks for the next event, as illustrated here:

On the other hand, a traditional system takes input(s) from a user, performs an operation based on inputs, and sends an output or response to the user; that's it:

In a Reactive system, the RP model eases the development. As a Reactive system supports abstraction at a very high level, it is easy to develop the applications because we need to concentrate on only our application business logic. Meanwhile, in a traditional system, we need to take care of the application business logic while writing some low-level logic, as it does not support high-level abstraction.

In a Reactive system, changes are propagated automatically. For instance, in a spreadsheet, we have a formula at cell A3, A3 =A1+A2. When we change the value of A1 or A2 or both, then all their references will be updated automatically. This means A3 will be updated automatically. It is not possible in a traditional system or non-Reactive system.

In Reactive systems, we concentrate on the flow of control, whereas in traditional systems, we concentrate on the flow of data.

The Java 9 Flow API

Oracle Corporation has introduced a new API for library or API developers to develop Reactive systems, Reactive libraries, Reactive data stores, Reactive servers, and so on. This API is also known as the Flow API.

It defines a set of interfaces to support developing Reactive systems, so it is also known as the Reactive Streams API. This API is defined under the java.util.concurrent package name.

The Java 9 Flow API mainly contains the following components:

  • Publisher
  • Subscriber
  • Subscription
  • Processor
  • Flow

The following diagram shows the main five components of the Java 9 Flow API:

Let's discuss these components of the Flow API one by one in detail in the following sections.

Flow API – Publisher

As its name suggests, Publisher is a component that works as a Producer of data, which means it emits the data. It acts as a source of data, so it is also known as Producer, Source of data, or emitter:

In the Java 9 Flow API, this Publisher is an interface with the subscribe method and is defined with the following signature:

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

Here, the subscribe() method is taking a single parameter of type Subscriber, which is another component of the Flow API. One publisher can subscribe one or more subscribers to it. It is defined within another class as a static component. We will see it in the following section.

Publisher uses this subscribe() method to subscribe or register its subscribers, as shown here.

Go through the following pseudo-code for Subscriber.subscribe() function usage:

Subscriber sub = Receive a Request from a Subscriber 
Publisher pub = ... 
pub.subscribe(sub) 

Publisher receives a request from a subscriber and executes pub.subscribe(sub) to register that subscriber with it. Once that subscription is created, the publisher sends data to those registered parties.

For instance, we can use a data store, file, collection, server, and more, as a source of data to emit data for subscribers.

Flow API – Subscriber

As its name says, the Subscriber is a component that works as a consumer of data. This means it consumes the data from a producer. It acts as a destination of data. So, it is also known as a consumer or destination of data:

In the Java 9 Flow API, this Subscriber is an interface with a set of methods and is defined as follows:

public static interface Subscriber<T> {   
  public void    onSubscribe(Subscription subscription);   
  public void    onNext(T item);   
  public void    onError(Throwable throwable);   
  public void    onComplete();   
}       

It has a set of methods:

  • onSubscribe(): This creates a new subscription. It is invoked prior to invoking any other Subscriber methods for the given Subscription.
  • onNext(): Once a Subscription is created, this is invoked to receive the next data, item, or element from the Publisher.
  • onError(): This is invoked upon an unrecoverable error encountered by a Publisher or Subscription, after which no other Subscriber methods are invoked by the Subscription.
  • onComplete(): This is invoked when there is no requirement to invoke any further Subscriber methods on that Subscription that is not already terminated in error, after which no other Subscriber methods are invoked by that Subscription.

It is also defined within another class as a static component. We will see it in the next section.

Flow API – Subscription

In the Flow API, a Subscription works as a mediator or interface between two other important components, Publisher and Subscriber. It connects those components and works as a message controller or channel so that a Publisher can emit data into a Subscription and one or more subscribers who subscribe to that Publisher and receive data from that Subscription:

In the Java 9 Flow API, this Subscription is an interface with a set of methods and is defined as follows:

public static interface Subscription {   
  public void    request(long n);   
  public void    cancel() ;   
}   

It contains the following two methods to control the messaging between Publisher and Subscriber(s):

  • request(): This is used to add the given n number of items to the current active Subscription between Publisher and Subscriber(s)
  • cancel(): This is used to cancel or stop the current Subscription between Publisher and Subscriber(s) so that there is no communication happening between them

One Subscription is dedicated between a Publisher and a single Subscriber or a set of Subscribers. Once it's stopped by making a call to the cancel() method, Publisher cannot send data to it or Subscriber cannot receive any messages from it.

It is also defined within another class as a static component. We will see it in the next section.

Flow API – Processor

In the Flow API, Processor is a special kind of component. It works as both a Subscriber and Publisher. We can use it as a source of data, that is, a Publisher, or a destination of data, that is, a Subscriber.

In the Java 9 Flow API, this Processor is an interface with no methods and is defined like this:

public interface Processor<T,R> extends Subscriber<T>, Publisher<R> {   
}  

It is also defined within another class as a static component. We will see it in the next section.

Flow API – Flow

In the previous sections, we discussed the components of the Flow API one by one in depth. They are all interfaces and are defined as static components within another component of the Flow API. This component is Flow.

In the Java 9 Flow API, this Flow component contains the rest of the four components' static components, as shown here:

Flow.java:

package java.util.concurrent; 
 
public final class Flow { 
 
    private Flow() {}  
   
    @FunctionalInterface 
    public static interface Publisher<T> { 
        public void subscribe(Subscriber<? super T> subscriber); 
    } 
 
    public static interface Subscriber<T> { 
 
        public void onSubscribe(Subscription subscription); 
 
        public void onNext(T item); 
 
        public void onError(Throwable throwable); 
 
        public void onComplete(); 
    } 
 
    public static interface Subscription { 
 
        public void request(long n); 
 
        public void cancel(); 
    } 
 
    public static interface Processor<T,R> extends Subscriber<T>,
Publisher<R> { } static final int DEFAULT_BUFFER_SIZE = 256; public static int defaultBufferSize() { return DEFAULT_BUFFER_SIZE; } }

This is so that we can access other components as Flow.xxxx, which means if we want to access a Publisher, we should use it like Flow.Publisher.

When we combine or connect all these components in a working system, we will see them as follows:

When we connect the Flow API components in this way, we can observe that a flow is going from source to destination. That's why they have named this API as the Flow API.

We can represent the Java 9 Flow API's Publisher/Subscriber complete communication as shown in the following diagram. This communication can end either successfully or in failure:

Implementations of Reactive Streams

In this section, we will discuss the most important and popular Reactive Streams Specification implementations, Reactive Technologies, and so on.

Lightbend's Reactive Platform

Lightbend's Reactive Platform is one of the popular technology stacks that support the FRP paradigm. Lightbend is one of the initiators of the Reactive Streams Specification. This platform has a Reactive microservice framework known as the Lagom framework.

The Lagom framework uses Scala, Play, and Akka Toolkit to develop Reactive systems, Reactive Web Applications, or Reactive microservices. It is a pure FRP Solution.

The Akka Toolkit has an API known as the Akka Streams API, which implements the Reactive Streams Specification.

In this book, we will use this technology stack to develop our Reactive system. Go through subsequent chapters to understand how to easily develop data streaming applications using Akka Streams and how to develop Reactive microservices using the Lagom framework.

Pivotal's Reactor project

The Pivotal team has developed a new module to support RP features, which is known as Reactor. They have released it as part of Spring Framework 5.x.

The Spring Framework is a Java framework to develop web applications, microserivces, and more. Its 5.x version is built on the Reactor module and also supports the API to develop Reactive applications. This module builds directly on the Reactive Streams Specification, so we don't need to use any bridge or adapters. Spring Framework has another module known as Reactor IO, which provides wrappers around low-level network runtimes, such as Netty and Aeron.

Microsoft's Reactive Extensions (RX)

Microsoft has implemented one Reactive Solution for C# (.Net platform) known as Reactive Extensions. It supports Reactive programming very well.

Reactive Extensions, Rx, or ReactiveX is a library to support asynchronous event-based programming, which has become a base library for other Rx libraries.

Netflix's RxJava

By following Microsoft's Rx library, Netflix has developed their own Rx library for the Java programming language, that is, RxJava.

RxJava stands for Reactive Extensions for Java. It became a base library for other JVM (Java Virtual Machine) languages. Many people have developed some adapters on top of this library.

For instance, RxScala is an Rx library for the Scala programming language. We will discuss Rx and the RxScala framework further in Chapter 5, Adding Reactiveness with RxScala.

Eclipse's Vert.x

Vert.x is an Eclipse Foundation project to support an Event-Driven paradigm on the JVM. Reactive support in Vert.x is similar to Ratpack. Vert.x allows us to use either RxJava or Eclipse native implementation of the Reactive Streams API to develop Reactive systems.

The Eclipse Vert.X website can be found at http://vertx.io/.

We can find its source code at https://github.com/eclipse/vert.x.

Ratpack

Ratpack is a set of Java libraries for building modern high-performance HTTP applications. It provides a basic implementation of the Reactive Streams specification. However, it is not designed to be a fully-featured RP Framework or toolkit.

We can get more information about Ratpack at https://ratpack.io/.

How are Reactive Streams born?

So far, we have discussed many things, such as Reactive programming, Reactive Manifest, the Reactive Streams API, the Java 9 Flow API, and finally, Reactive implementations, in detail in the previous sections.

It is useful to understand how they are all related and why they are required. I prefer a simple diagram to explain it instead of a lengthy description.

Take a look at the following diagram:

I hope you understood well how the Reactive Streams API was born. In my point of view, there are four phases or stages of the Reactive Streams API.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • - Understand and use the concepts of reactive programming to build distributed systems running on multiple nodes.
  • - Learn how reactive architecture reduces complexity throughout the development process.
  • - Get to grips with functional reactive programming and Reactive Microservices.

Description

Reactive programming is a scalable, fast way to build applications, and one that helps us write code that is concise, clear, and readable. It can be used for many purposes such as GUIs, robotics, music, and others, and is central to many concurrent systems. This book will be your guide to getting started with Reactive programming in Scala. You will begin with the fundamental concepts of Reactive programming and gradually move on to working with asynchronous data streams. You will then start building an application using Akka Actors and extend it using the Play framework. You will also learn about reactive stream specifications, event sourcing techniques, and different methods to integrate Akka Streams into the Play Framework. This book will also take you one step forward by showing you the advantages of the Lagom framework while working with reactive microservices. You will also learn to scale applications using multi-node clusters and test, secure, and deploy your microservices to the cloud. By the end of the book, you will have gained the knowledge to build robust and distributed systems with Scala and Akka.

Who is this book for?

This book is for Scala developers who would like to build fault-tolerant, scalable distributed systems. No knowledge of Reactive programming is required.

What you will learn

  • Understand the fundamental principles of Reactive and Functional programming
  • Develop applications utilizing features of the Akka framework
  • Explore techniques to integrate Scala, Akka, and Play together
  • Learn about Reactive Streams with real-time use cases
  • Develop Reactive Web Applications with Play, Scala, Akka, and Akka Streams
  • Develop and deploy Reactive microservices using the Lagom framework and ConductR
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 28, 2018
Length: 552 pages
Edition : 1st
Language : English
ISBN-13 : 9781787288645
Vendor :
Lightbend
Category :
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Feb 28, 2018
Length: 552 pages
Edition : 1st
Language : English
ISBN-13 : 9781787288645
Vendor :
Lightbend
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 $ 146.97
Scala Design Patterns
$48.99
Scala Reactive Programming
$48.99
Learning Scala Programming
$48.99
Total $ 146.97 Stars icon
Banner background image

Table of Contents

15 Chapters
Getting Started with Reactive and Functional Programming Chevron down icon Chevron up icon
Functional Scala Chevron down icon Chevron up icon
Asynchronous Programming with Scala Chevron down icon Chevron up icon
Building Reactive Applications with Akka Chevron down icon Chevron up icon
Adding Reactiveness with RxScala Chevron down icon Chevron up icon
Extending Applications with Play Chevron down icon Chevron up icon
Working with Reactive Streams Chevron down icon Chevron up icon
Integrating Akka Streams to Play Application Chevron down icon Chevron up icon
Reactive Microservices with Lagom Chevron down icon Chevron up icon
Testing Reactive Microservices Chevron down icon Chevron up icon
Managing Microservices in ConductR Chevron down icon Chevron up icon
Reactive Design Patterns and Best Practices Chevron down icon Chevron up icon
Scala Plugin for IntelliJ IDEA Chevron down icon Chevron up icon
Installing Robomongo Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8
(10 Ratings)
5 star 40%
4 star 0%
3 star 10%
2 star 0%
1 star 50%
Filter icon Filter
Top Reviews

Filter reviews by




Kishore Apr 01, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is great book to start and get understanding of scala reactive programming, each chapter has a detailed explanation with nice diagrams and examples, the topics are well organized and moving slowly from fundamental concepts to building robust systems with Scala and Akka and deploying your microservices to cloud, the summary in each chapter is very organized and connecting to previous and next learning highlights, the book is very impressive and I would recommend to read once in order to explore and develop reactive web applications with Play, Scala, Akka, and Akka Streams
Amazon Verified review Amazon
LoyalAmazonCustomer Apr 22, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
very nicely written and articulated the concepts. Good start for readers who are interested in reactive programming in Scala and Akka, as well deploying microservices in cloud. One of the great books i have read in recent years and would highly recommend to others.
Amazon Verified review Amazon
Bhavs Apr 19, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a very nice book. This book covered all the topics starting from reactive programming to in-depth knowledge of reactive programming.It seems, The author has tremendous experience in both software engineering and teaching.This covers building Reactive Applications with Akka. It's good book and worth reading.
Amazon Verified review Amazon
Amazon Customer Apr 09, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is very usefull for people who are desperate of working on Microservices
Amazon Verified review Amazon
Szilágyi Donát Jun 12, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The topics are good and the first part about Scala is a really good summary about this huge programming language. What I missed is the more practical info about setting up the environment and configuring the frameworks. Some of them (especially Lagom) was very difficult to start based on the info in this book. Sometimes I lost among the version numbers of Scala, SBT and the frameworks. But the code examples are practical and easy to understand.
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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela