Reactive Programming – Intro

October 7, 2018

Why? Why do we need Reactive programming?

We all know the phrase: “If it is not broken don’t fix it”. So what is the problem for which we need a solution? Because if there is no problem, we don’t need a solution.
That we need asynchronous programming, we can all agree. So the question is, why do we need Reactive programming and why cannot we just use Futures, especially CompletableFutures (Futures inspired by Google’s Listenable Futures from the Guava library which support chaining tasks together via supplyAsync and thenApply or thenApplyAsync) or Java9’s Flow API.
RxJava at a first glance will looks like Streams, but it is more powerful. RxJava can be used for chaining together synchronous or asynchronous actions to produce one or more meaningful results. However unlike Futures, which are single-use, RxJava works on streams of zero or more items including never-ending streams with an infinite number of items.
The Flow API is more simple, but this simplicity means less tools to work with. Besides the Flow API is an interoperation specification and not an end-user API. This means that you would not want to use it directly, but wait until implementations of it are ready.

How to set up an RxJava2 project

The RxJava2 artifact can be found here.
Maven Dependency:

<dependencies>
    <dependency>
        <groupId>io.reactivex.rxjava2</groupId>
        <artifactId>rxjava</artifactId>
        <version>2.2.2</version>
    </dependency>
</dependencies>

First RxJava code

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("A", "B", "C", "D", "E");

        myObservable.subscribe(System.out::println);
    }

}

When we run this code, it will print out the five Strings. So what do we have here?
Observables represent asynchronous data streams. When we subscribed to the observable, it pushed the String objects (which are called emissions) via the subscribe method by passing a Lambda expression.

First RxJava operator

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args) {
        Observable<String> myObservable = Observable.just("A", "BB", "CCC", "DDDD", "EEEEE");

        myObservable
          .map(String::length)
          .subscribe(System.out::println);
    }

}

Several operators can be used to transform or manipulate each pushed item. Each operator returns a new Observable that reflects the transformation.
In the example above, with the help of the map method, each emission is transformed with the length() method. Then, each Integer is pushed to the Observer.

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami