Skip to main content

A Brief Introduction to RxJava2.x






Reactive programming is a programming style where the consumer reacts to the data as it comes in. Asynchronous programming is also called reactive programming. In reactive a programming observables are allowed to propagate event changes to registered observers.

"The Observer pattern has done right. ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming."

Building blocks for RxJava2.x

Observables : Representing sources of data

Subscribers (or observers) : Listens to the observables

Methods : A set of methods for modifying and composing the data

An observable emits items; a subscriber consumes those items.

Observables :

As mentioned above Observables are the sources for the data. Observable objects that emit a stream of data and then terminate. It can terminate either successfully or with an error.

Subscribers :

A subscriber objects that subscribe to Observables. An Observer receives a notification each time their assigned Observable emits a value, an error, or a completed signal.

The need for asynchronous programming

Asynchronous programming refers to a style of structuring a program whereby a call to some unit of functionality triggers an action that is allowed to continue outside of the ongoing flow of the program.

In the simple word when we get a task which may take a long time like I/O operations, HTTP calls, Database calls its preferred perform it outside the ongoing flow.

Reactive programming facilitates a simple way of asynchronous programming. It also provides a defined way of handling multiple events, errors and termination of the event stream. Reactive programming also makes simple the way of running different tasks in different threads.

Using reactive programming it is also possible to convert the stream before its received by the observers. Also, you can chain operations, e.g., if an API call depends on the call of another API Last but not least, reactive programming reduces the need for state variables, which can be the source of errors.

Adding RxJava2.x to a Java/Android project

For Gradle :

compile group: 'io.reactivex.rxjava2', name: 'rxjava', version: '2.1.1'

For Android :

compile 'io.reactivex.rxjava2:rxjava:2.0.8'

For Maven :

    io.reactivex.rxjava2
    rxjava
    2.0.4

High level steps for RxJava2.x

  • Creating an Observable.
  • Giving that Observable some data to emit.
  • Creating an Observer.
  • Assigning the Observer to an Observable.
  • Giving the Observer tasks to perform whenever it receives an emission from its assigned Observable.
Obervable types
Type Description
Flowable
Emits 0 or n items and terminates with a success or an error event. Supports backpressure, which allows controlling how fast a source emits items.
Observable
Emits 0 or n items and terminates with a success or an error event.
Single
Emits either a single item or an error event. The reactive version of a method call.
Maybe
Succeeds with an item, or no item, or errors. The reactive version of an Optional.
Completable
Either complete with a success or with an error event. It never emits items. The reactive version of a Runnable.

Android Example :

Creating observable

Observable observable = Observable.create(new ObservableOnSubscribe() {
       @Override
       public void subscribe(ObservableEmitter
e) throws Exception {
       
       //Use onNext to emit each item in the stream//
              e.onNext(1);
              e.onNext(2);
              e.onNext(3);
              e.onNext(4);
              //Once the Observable has emitted all items in the sequence, call onComplete//
              e.onComplete();
       }
});
or Using lambdas, the same statement can be expressed as:
Observable observable = Observable.create(e -> {
       e.onNext(1);
       e.onNext(2);

       e.onNext(3);
       e.onNext(4);
       //Once the Observable has emitted all items in the sequence, call onComplete//
       e.onComplete();
});

Creating an Observer

Observer observer = new Observer() {
       @Override
       public void onSubscribe(Disposable d) {
              
Log.e(TAG, "onSubscribe: ");
       }
       @Override
       public void onNext(Integer value) {
       
       Log.e(TAG, "onNext: " + value);
       }
       @Override
       public void onError(Throwable e) {
       
       Log.e(TAG, "onError: ");
       }
       @Override
       public void onComplete() {
       
       Log.e(TAG, "onComplete: All Done!");
       }
};
//Create our subscription//
observable.subscribe(observer);

Some other Convenience methods to create observables :

RxJava provides several convenience methods to create observables

Observable.just("Hello")
- Allows to create an observable as wrapper around other data types

Observable.fromIterable()
- takes an java.lang.Iterable and emits their values in their order in the data structure

Observable.fromArray() - takes an array and emits their values in their order in the data structure

Observable.fromCallable() - Allows to create an observable for a java.util.concurrent.Callable

Observable.fromFuture() - Allows to create an observable for a java.util.concurrent.Future

Observable.interval() - An observable that emits Long objects in a given interval

Similar methods exists for the other data types, 

e.g., *Flowable.just(), Maybe.just() and Single.just.

Unsubscribe to avoid memory leaks

Observable.subscribe() returns a Subscription (if you are using a Flowable) or a Disposable object. To prevent a possible (temporary) memory leak, unsubscribe from your observables in the`onStop()` method of the activity or fragment. For example, for a Disposable object you could do the following:
if (subscription != null && !subscription.isDisposed()) {
       subscription.dispose();
}

References : 
https://github.com/ReactiveX/RxJava
http://www.vogella.com
https://code.tutsplus.com





Comments

Post a Comment

Popular posts from this blog

Future of Mobile Apps

More than 1 billion smartphones and 179 billion mobile applications downloaded per year, mobile development is certainly one of the innovative and rapidly growing sector. The mobile application market is arguably dominated by Google apps (Gmail, Maps, Search), Social media (Facebook, Instagram, Twitter, Youtube) and Gaming apps (Angry birds, Temple Run). Giants like Walmart, Bank of America and Amazon are using mobile applications for branding, improving customer engagement, direct marketing etc. This trend will continue in 2017 as well. There are lots of opportunities for startups and small companies. 1. AI will attract huge investment Industry analyst firms Granter and Forrester have revealed that there will be a 300% increase in investment in artificial intelligence. This is because business users now have unique and very powerful insights open to them. For example, giants like Facebook, Google and IBM are already investing in technologies (by acquiring startups) that would get ...

Introduction to Kotlin : New Official Programming Language for Android

Kotlin is a statically-typed programming language primarily developed by the team of JetBrains that runs on the Java Virtual Machine and also can be compiled to JavaScript source code or uses the LLVM compiler infrastructure. It's a modern programming language. Development lead Andrey Breslav has said that Kotlin is designed to be an industrial-strength object-oriented language, and a "better language" than Java, but still be fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin. Kotlin can be adopted for both sides of development backend and front end. One of the obvious applications of Kotlin is Android development. Android has announced Kotlin as it's official language in Google I/O 2017. Why I should adopt Kotlin : Although Java is one of the world's most widely used programming languages and is pretty much the official language for Android development, there are many reasons why Java might not always ...

15 Key tips to reduce your Android App Size

Users often avoid downloading apps that seem too large, particularly in emerging markets where devices connect to often-spotty 2G and 3G networks or work on pay-by-the-byte plans. This article describes how to reduce your app's APK size, which enables more users to download your app. Understand the APK Structure Before discussing how to reduce the size of your app, it's helpful to understand the structure of an app's APK. An APK file consists of a ZIP archive that contains all the files that comprise your app. These files include Java class files, resource files, and a file containing compiled resources. An APK contains the following directories: META-INF/:   Contains the CERT.SF and CERT.RSA signature files, as well as the  MANIFEST.MF  manifest file. assets/:   Contains the app's assets, which the app can retrieve using an AssetManager object. res/:   Contains resources that aren't compiled into resources.arsc. lib/:   Contains the co...