A simple RxJava 2 “Hello, world” example

As a brief note, and assuming that you already know a little bit about RxJava, here’s the simplest possible RxJava 2 “Hello, world” example I think you can create:

package hello;

import io.reactivex.Observable;

public class HelloWorld {

    public static void main(String[] args) {
        Observable<String> observable = Observable.just("Hello, world");
        observable.subscribe(System.out::println);
    }

}

I used Gradle to run this code, so all I had to do was create a Gradle/Java project like this:

mkdir HelloWorld
cd HelloWorld
gradle init --type java-application

and then add this line to the dependencies section of the build.gradle file:

implementation 'io.reactivex.rxjava2:rxjava:2.2.0'

Then I put that source code in a src/main/java/hello/HelloWorld.java file, and then ran:

gradle run

and everything worked as advertised.

subscribe with Lambda syntax

Before I go, it’s worth noting that you can also write that subscribe method like this, if you prefer:

observable.subscribe(s -> System.out.println(s)); 

In summary, if you wanted to see a simple RxJava 2 “Hello, world” example, I hope this is helpful.