RxJava2 is the library for Reactive programming in Java. Let’s get started with a very simple piece of code.
In Reactive Programming, we have a publisher and a subscriber. Publisher publishes(or Pushes) data to a subscriber. When the subscriber receives data, it Reacts.
Include the RxJava2 library. The pom.xml is shown below. We need Java 8 and above.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.healthycoder</groupId>
<artifactId>Reactive_Java</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
We’ll create a class HelloWorld and create a publisher and subscriber as shown below.
package com.healthycoder;
import io.reactivex.Observable;
public class HelloWorld {
public static void main(String[] args) throws Exception{
Observable<String> producer = Observable.just("Hello World");
producer.subscribe(System.out::println);
}
}
Yes!!! You’re right. We are implementing Observer Pattern here. Reactive programming to begin with is termed as “Observer pattern done right”. We have created an Observable stream that pushes strings. We have a subscriber who just prints it!!!
Alright we have taken the first step into reactive world. Let’s take baby steps. One piece at a time 