rx-java Getting started with rx-java An introduction to RxJava


Example

The core concepts of RxJava are its Observables and Subscribers. An Observable emits objects, while a Subscriber consumes them.

Observable

Observable is a class that implements the reactive design pattern. These Observables provide methods that allow consumers to subscribe to event changes. The event changes are triggered by the observable. There is no restriction to the number of subscribers that an Observable can have, or the number of objects that an Observable can emit.

Take for example:

Observable<Integer> integerObservable = Observable.just(1, 2, 3); // Integer observable
Observable<String> stringObservable = Observable.just("Hello, ", "World", "!"); // String observable

Here, an observable object called integerObservable and stringObservable are created from the factory method just provided by the Rx library. Notice that Observable is generic and can thus can emit any object.

Subscriber

A Subscriber is the consumer. A Subscriber can subscribe to only one observable. The Observable calls the onNext(), onCompleted(), and onError() methods of the Subscriber.

Subscriber<Integer> mSubscriber = new Subscriber<Integer>() {
        // NOTE THAT ALL THESE ARE CALLED BY THE OBSERVABLE
        @Override
        public void onCompleted() {
            // called when all objects are emitted
            System.out.println("onCompleted called!");
        }

        @Override
        public void onError(Throwable throwable) {
            // called when an error occurs during emitting objects
            System.out.println("onError called!");
        }

        @Override
        public void onNext(Integer integer) {
            // called for each object that is emitted
            System.out.println("onNext called with: " + integer);
        }
    };

Notice that Subscriber is also generic and can support any object. A Subscriber must subscribe to the observable by calling the subscribe method on the observable.

integerObservable.subscribe(mSubscriber);

The above, when run, will produce the following output:

onNext called with: 1
onNext called with: 2
onNext called with: 3
onCompleted called!