Reactive Programming (Rx) is a declarative programming paradigm concerned with data streams and the propagation of change. In reactive programming, data streams are spine of application. Events, messages, calls, and even failures are going to be conveyed by a data stream. With reactive programming, you observe these streams and react when a value is emitted.

In Rx programming data flows emitted by one component and the underlying structure provided by the Rx libraries will propagate those changes to another component those are registered to receive those data changes.

Key Component

It is made up of following key component

  • Observable: They are data streams. It packs the data that can be passed around from one thread to another thread. It can emit data in various scenarios, for example specific data based on certain events. In other words observable are suppliers. They process and supply the data to other components.
  • Observers: It consumes the data stream emitted by the observable. They subscribe to the observable method to receive the data emitted by the observable. Whenever the observable emits the data all the registered observer receives the data in callback specified during registration.
  • Schedulers: Rx is for asynchronous programming, so we need thread management. Thread management is done by schedulers. They tells observable and observers, on which thread they should run.

ReactiveX

ReactiveX extension is an implementation of the reactive programming principles. It provides toolbox to creates and subscribes to data streams named Observables.

Below example shows reactive programming example, implemented Java library of ReactiveX extension.

// Observable, it will emit the data
Observable<String> numbers = Observable.just(new String[]{"1", "2", "3", "4"}); 

 Observer<String> observer = new Observer<String>() {

   @Override
    public void onCompleted() {
        //...
    }

    @Override
    public void onError(Throwable e) {
        //...
    }

    @Override
    public void onNext(String s) {
        //...
    }
};

numbers.subscribeOn(Schedulers.newThread())         // Observable runs on new background thread.
        .observeOn(AndroidSchedulers.mainThread())    // Observer will run on main UI thread.
        .subscribe(observer);                                                // Subscribe the observer

In above example, numbers is an observable which emits the data. just() is an operator, which emits the data provided in the argument one by one. observer is an observer that consumes the data emitted by numbers observable. It processes the data received and also handles error inside it.

At the last step, schedulers are defined. It manage the thread concurrency. subscribeOn(Schedulers.newThread()) tells observable to run on background thread. observeOn(AndroidSchedulers.mainThread()) tells observer to run on the main thread.