RxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences.
The build blocks for RxJava code are the following:
- observables representing sources of data
- subscribers (or observers) listening to the observables
- a set of methods for modifying and composing the data
Add dependency for Rx java in build.gradle.
1 2 |
compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'io.reactivex.rxjava2:rxjava:2.1.0' |
Observable just produces an Observable that emits a single generic instance. For example:
1 2 3 4 5 6 7 |
Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception { e.onNext("hello"); e.onNext("world"); } }); |
Create an instance of Observer to get the data from the data source (Observable). The data source push data to onNext() method in the observer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Observer<String> observer = new Observer<String>() { @Override public void onSubscribe(@NonNull Disposable d) { Log.d(TAG, "onSubscribe: "+d); } @Override public void onNext(@NonNull String integer) { Log.d(TAG, "onNext: "+integer); } @Override public void onError(@NonNull Throwable e) { Log.d(TAG, "onError: "+e); } @Override public void onComplete() { Log.d(TAG, "onComplete: "+"DONE ALL WORK RXJAVA"); } }; |
Once the observable instance initialised subscribe the observer.
1 |
observable.subscribe(observer); |
OUTPUT: hello world
Advantages of RxJava
Some advantages of RxJava are the following:
- You can chain async operations, e.g., if a API call depends on the call of another API
- A defined way to handle errors
- It reduces the need for state variables, which can be the source of errors == Creating sources, subscribing to them and disposing them