Introduction to RxJava

Yaroslav Heriatovych

RxJava

 is a library for composing asynchronous and event-based programs by using observable sequences.

Event-based system

The notion of time

Ordered sequence

  • Is it a List?
  • Is it a Iterable?
  • It's Observable!

Event-based system

Observable




Observables fill the gap by being the ideal implementation of access to asynchronous sequences of multiple items
single items multiple items
synchronous T getData() Iterable<T> getData()
asynchronous Future<T> getData() Observable<T> getData()

Observable

Primitives

 public interface Observer <T>  {
    void onCompleted();
    void onError(java.lang.Throwable throwable);
    void onNext(T t);
 }
public class Observable <T>  {
    public final static <T> Observable<T> create(OnSubscribe<T> f)
    public rx.Subscription subscribe(rx.Observer<? super T> observer)
    // ... 
}

public static interface OnSubscribe<T> extends Action1<Subscriber<? super T>> {}

public interface Subscription {
    public void unsubscribe();
    public boolean isUnsubscribed();
}
public abstract class Subscriber<T> implements Observer<T>, Subscription {...}

Create Observable

Observable<String> o = Observable.from("a", "b", "c");
Observable<String> o = Observable.just("one object"); 

Observable<String> o = Observable.create(new Observable.OnSubscribe<String>() {
    @Override                                                                  
    public void call(Subscriber<? super String> subscriber) {                  
        subscriber.onNext("Hello");                                            
        subscriber.onNext("World");                                            
        subscriber.onCompleted();                                              
    }                                                                          
});                                                                            

Subscribe

obs.subscribe(new Observer<String>() {                       
    @Override                                                
    public void onCompleted() {                              
        System.out.println("completed");                     
    }                                                        
                                                             
    @Override                                                
    public void onError(Throwable e) {                       
        e.printStackTrace();                                 
    }                                                        
                                                             
    @Override                                                
    public void onNext(String s) {                           
        System.out.println("item " + s);                     
    }                                                        
});
                                                          
obs.subscribe(                                               
        (String s) -> System.out.println("item " + s),       
        (Throwable t) -> t.printStackTrace()                 
);
                                                           
obs.subscribe((String s) -> System.out.println("item " + s));

Subscription

Subscription subscription = obs.subscribe(s -> System.out.println(s));
//...somewhere else        
subscription.unsubscribe();

Transform Observable

public Observable<Integer> mapLength(Observable<String> source) {
    return Observable.create(subscriber ->                       
            source.subscribe(new Observer<String>() {            
                @Override                                        
                public void onCompleted() {                      
                    subscriber.onCompleted();                    
                }                                                
                                                                 
                @Override                                        
                public void onError(Throwable e) {               
                    subscriber.onError(e);                       
                }                                                
                                                                 
                @Override                                        
                public void onNext(String s) {                   
                    subscriber.onNext(s.length());               
                }                                                
            }));                                                 
}                                                                

map

Observable<Integer> lengthObservable = source.map(s -> s.length());

filter

take

scan

reduce

merge

zip

flatMap

map + merge

Composition

request1()                                                     
    .flatMap(result1 -> request2(result1))                     
    .flatMap(result2 -> request3(result2))                     
    .subscribe(finalResult -> System.out.println(finalResult));

Error Handling

retry

retryWhen

onErrorReturn

onErrorResumeNext

Execution Context

Observable<String> observable =                                 
        Observable.create(new Observable.OnSubscribe<String>() {
    @Override                                                   
    public void call(Subscriber<? super String> subscriber) {   
        subscriber.onNext("Hello");                             
        subscriber.onNext("World");                          
        subscriber.onCompleted();                               
    }                                                           
});                                                             

Simple Observable

observable.subscribe(new Action1<String>() {
    @Override                               
    public void call(String s) {            
        handleString(s);                    
    }                                       
});                                         

Schedulers

observable                               
        .map(x -> heavyTransformation(x))
        .subscribe(System.out::println); 
observable                                  
        .observeOn(Schedulers.computation())
        .map(x -> heavyTransformation(x))   
        .observeOn(Schedulers.newThread())  
        .subscribe(System.out::println);    

Schedulers

Schedulers.computation(); 
Schedulers.io();          
Schedulers.newThread();   
Schedulers.from(executor);
observable.subscribeOn(scheduler)  
observable.observeOn(scheduler)   
observable.unsubscribeOn(scheduler)

Build-in Schedulers

Operators

RxJava

Not only for Java

Language adapters

  • RxScala
  • RxClojure
  • RxGroovy
  • RxKotlin
  • RxJRuby

Questions?

Links

Introduction to RxJava

By Yaroslav Heriatovych

Introduction to RxJava

  • 4,484