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.
The full source code for the project including all the code samples used here can be found over on Github.