Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
1. Overview
In this article, weβre going to focus on using Reactive Extensions (Rx) in Java to compose and consume sequences of data.
At a glance, the API may look similar to Java 8 Streams, but in fact, it is much more flexible and fluent, making it a powerful programming paradigm.
If you want to read more about RxJava, check out this writeup.
2. Setup
To use RxJava in our Maven project, weβll need to add the following dependency to our pom.xml:
<dependency>
<groupId>io.reactivex</groupId>
<artifactId>rxjava</artifactId>
<version>${rx.java.version}</version>
</dependency>
Or, for a Gradle project:
compile 'io.reactivex.rxjava:rxjava:x.y.z'
3. Functional Reactive Concepts
On one side, functional programming is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects.
On the other side, reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change.
Together, functional reactive programming forms a combination of functional and reactive techniques that can represent an elegant approach to event-driven programming β with values that change over time and where the consumer reacts to the data as it comes in.
This technology brings together different implementations of its core principles, some authors came up with a document that defines the common vocabulary for describing the new type of applications.
3.1. Reactive Manifesto
The Reactive Manifesto is an online document that lays out a high standard for applications within the software development industry. Simply put, reactive systems are:
- Responsive β systems should respond in a timely manner
- Message Driven β systems should use async message-passing between components to ensure loose coupling
- Elastic β systems should stay responsive under high load
- Resilient β systems should stay responsive when some components fail
4. Observables
There are two key types to understand when working with Rx:
- Observable represents any object that can get data from a data source and whose state may be of interest in a way that other objects may register an interest
- An observer is any object that wishes to be notified when the state of another object changes
An observer subscribes to an Observable sequence. The sequence sends items to the observer one at a time.
The observer handles each one before processing the next one. If many events come in asynchronously, they must be stored in a queue or dropped.
In Rx, an observer will never be called with an item out of order or called before the callback has returned for the previous item.
4.1. Types of Observable
There are two types:
- Non-Blocking β asynchronous execution is supported and is allowed to unsubscribe at any point in the event stream. On this article, weβll focus mostly on this kind of type
- Blocking β all onNext observer calls will be synchronous, and it is not possible to unsubscribe in the middle of an event stream. We can always convert an Observable into a Blocking Observable, using the method toBlocking:
BlockingObservable<String> blockingObservable = observable.toBlocking();
4.2. Operators
An operator is a function that takes one Observable (the source) as its first argument and returns another Observable (the destination). Then for every item that the source observable emits, it will apply a function to that item, and then emit the result on the destination Observable.
Operators can be chained together to create complex data flows that filter event based on certain criteria. Multiple operators can be applied to the same observable.
It is not difficult to get into a situation in which an Observable is emitting items faster than an operator or observer can consume them. You can read more about back-pressure here.
4.3. Create Observable
The basic operator just produces an Observable that emits a single generic instance before completing, the String βHelloβ. When we want to get information out of an Observable, we implement an observer interface and then call subscribe on the desired Observable:
Observable<String> observable = Observable.just("Hello");
observable.subscribe(s -> result = s);
assertTrue(result.equals("Hello"));
4.4. OnNext, OnError, and OnCompleted
There are three methods on the observer interface that we want to know about:
- OnNext is called on our observer each time a new event is published to the attached Observable. This is the method where weβll perform some action on each event
- OnCompleted is called when the sequence of events associated with an Observable is complete, indicating that we should not expect any more onNext calls on our observer
- OnError is called when an unhandled exception is thrown during the RxJava framework code or our event handling code
The return value for the Observables subscribe method is a subscribe interface:
String[] letters = {"a", "b", "c", "d", "e", "f", "g"};
Observable<String> observable = Observable.from(letters);
observable.subscribe(
i -> result += i, //OnNext
Throwable::printStackTrace, //OnError
() -> result += "_Completed" //OnCompleted
);
assertTrue(result.equals("abcdefg_Completed"));
5. Observable Transformations and Conditional Operators
5.1. Map
The map operator transforms items emitted by an Observable by applying a function to each item.
Letβs assume there is a declared array of strings that contains some letters from the alphabet and we want to print them in capital mode:
Observable.from(letters)
.map(String::toUpperCase)
.subscribe(letter -> result += letter);
assertTrue(result.equals("ABCDEFG"));
The flatMap can be used to flatten Observables whenever we end up with nested Observables.
More details about the difference between map and flatMap can be found here.
Assuming we have a method that returns an Observable<String> from a list of strings. Now weβll be printing for each string from a new Observable the list of titles based on what Subscriber sees:
Observable<String> getTitle() {
return Observable.from(titleList);
}
Observable.just("book1", "book2")
.flatMap(s -> getTitle())
.subscribe(l -> result += l);
assertTrue(result.equals("titletitle"));
5.2. Scan
The scan operator applies a function to each item emitted by an Observable sequentially and emits each successive value.
It allows us to carry forward state from event to event:
String[] letters = {"a", "b", "c"};
Observable.from(letters)
.scan(new StringBuilder(), StringBuilder::append)
.subscribe(total -> result += total.toString());
assertTrue(result.equals("aababc"));
5.3. GroupBy
Group by operator allows us to classify the events in the input Observable into output categories.
Letβs assume that we created an array of integers from 0 to 10, then apply group by that will divide them into the categories even and odd:
Observable.from(numbers)
.groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
.subscribe(group ->
group.subscribe((number) -> {
if (group.getKey().toString().equals("EVEN")) {
EVEN[0] += number;
} else {
ODD[0] += number;
}
})
);
assertTrue(EVEN[0].equals("0246810"));
assertTrue(ODD[0].equals("13579"));
5.4. Filter
The operator filter emits only those items from an observable that pass a predicate test.
So letβs filter in an integer array for the odd numbers:
Observable.from(numbers)
.filter(i -> (i % 2 == 1))
.subscribe(i -> result += i);
assertTrue(result.equals("13579"));
5.5. Conditional Operators
DefaultIfEmpty emits item from the source Observable, or a default item if the source Observable is empty:
Observable.empty()
.defaultIfEmpty("Observable is empty")
.subscribe(s -> result += s);
assertTrue(result.equals("Observable is empty"));
The following code emits the first letter of the alphabet βaβ because the array letters is not empty and this is what it contains in the first position:
Observable.from(letters)
.defaultIfEmpty("Observable is empty")
.first()
.subscribe(s -> result += s);
assertTrue(result.equals("a"));
TakeWhile operator discards items emitted by an Observable after a specified condition becomes false:
Observable.from(numbers)
.takeWhile(i -> i < 5)
.subscribe(s -> sum[0] += s);
assertTrue(sum[0] == 10);
Of course, there more others operators that could cover our needs like Contain, SkipWhile, SkipUntil, TakeUntil, etc.
6. Connectable Observables
A ConnectableObservable resembles an ordinary Observable, except that it doesnβt begin emitting items when it is subscribed to, but only when the connect operator is applied to it.
In this way, we can wait for all intended observers to subscribe to the Observable before the Observable begins emitting items:
String[] result = {""};
ConnectableObservable<Long> connectable
= Observable.interval(200, TimeUnit.MILLISECONDS).publish();
connectable.subscribe(i -> result[0] += i);
assertFalse(result[0].equals("01"));
connectable.connect();
Thread.sleep(500);
assertTrue(result[0].equals("01"));
7. Single
Single is like an Observable who, instead of emitting a series of values, emits one value or an error notification.
With this source of data, we can only use two methods to subscribe:
- OnSuccess returns a Single that also calls a method we specify
- OnError also returns a Single that immediately notifies subscribers of an error
String[] result = {""};
Single<String> single = Observable.just("Hello")
.toSingle()
.doOnSuccess(i -> result[0] += i)
.doOnError(error -> {
throw new RuntimeException(error.getMessage());
});
single.subscribe();
assertTrue(result[0].equals("Hello"));
8. Subjects
A Subject is simultaneously two elements, a subscriber and an observable. As a subscriber, a subject can be used to publish the events coming from more than one observable.
And because itβs also observable, the events from multiple subscribers can be reemitted as its events to anyone observing it.
In the next example, weβll look at how the observers will be able to see the events that occur after they subscribe:
Integer subscriber1 = 0;
Integer subscriber2 = 0;
Observer<Integer> getFirstObserver() {
return new Observer<Integer>() {
@Override
public void onNext(Integer value) {
subscriber1 += value;
}
@Override
public void onError(Throwable e) {
System.out.println("error");
}
@Override
public void onCompleted() {
System.out.println("Subscriber1 completed");
}
};
}
Observer<Integer> getSecondObserver() {
return new Observer<Integer>() {
@Override
public void onNext(Integer value) {
subscriber2 += value;
}
@Override
public void onError(Throwable e) {
System.out.println("error");
}
@Override
public void onCompleted() {
System.out.println("Subscriber2 completed");
}
};
}
PublishSubject<Integer> subject = PublishSubject.create();
subject.subscribe(getFirstObserver());
subject.onNext(1);
subject.onNext(2);
subject.onNext(3);
subject.subscribe(getSecondObserver());
subject.onNext(4);
subject.onCompleted();
assertTrue(subscriber1 + subscriber2 == 14)
9. Resource Management
Using operation allows us to associate resources, such as a JDBC database connection, a network connection, or open files to our observables.
Here weβre presenting in commentaries the steps we need to do to achieve this goal and also an example of implementation:
String[] result = {""};
Observable<Character> values = Observable.using(
() -> "MyResource",
r -> {
return Observable.create(o -> {
for (Character c : r.toCharArray()) {
o.onNext(c);
}
o.onCompleted();
});
},
r -> System.out.println("Disposed: " + r)
);
values.subscribe(
v -> result[0] += v,
e -> result[0] += e
);
assertTrue(result[0].equals("MyResource"));
10. Conclusion
In this article, we have talked how to use RxJava library and also how to explore its most important features.
