Gradle Hello World project with RxJava

RxJava is the Java implementation of Rx Framework which was developed at Microsoft. It'a a library that allows you build reactive systems.

Step 1. Create Java QuickStart project

Create a Gradle project, using the QuickStart template

Step 2. Add RxJava dependencies

Open your build.gradle file and add a line in dependencies block

 
dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    compile 'io.reactivex:rxjava:1.0.14'
}
 
 

And don't forget to set the source compatiblity to higher than 1.5. Because you will need to implements and override the call method of Func1 class. If you are using Java 8, this can be written in Lambda expression, but if you are using Java 7 and lower version, you need to use anonymous class.

 
sourceCompatibility = 1.7
 

Step 3. Add test class

First create a new package, for example com.makble.rxexamples

Add a class for example RxTest

 
package com.makble.rxexamples;
 
import java.util.Arrays;
 
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
 
public class RxTest {
    public static void main (String [] args){
 
        Integer[] numbers = {1,2 ,3,4};
        Observable<Integer> source = Observable.from(numbers);
 
        source.map(new Func1<Integer, Integer>(){
            @Override
            public Integer call(Integer i){
                return i + 3;
            }
        })
        .subscribe(new Action1<Integer>(){
            public void call(Integer i){
                System.out.println(i);
            }
        });
    }
}
 
 

We are creating observable object and apply the map operator on it then in subscription we print the value of itmes in the observable sequence.