The Missing RxJava 2 Guide to Supercharge Your Android Development (Part 1)

Aritra Roy
Aritra's Musings
Published in
9 min readOct 13, 2017

--

RxJava has always been known to scare the hell out of many developers. I know, it seems quite overwhelming in the beginning, but once you start understanding it, you will literally get addicted to it.

RxJava 2 was released some time back, featuring a major rewrite of the entire library from scratch. But without an in-depth and proper understanding of the fundamental concepts of reactive programming, you are not going to get far enough with RxJava for Android development.

The main goal of this article is to get into the depths of the various core concepts of reactive programming and fundamentals of RxJava and make them crystal clear in your head once and for all, with the help of several real-world examples and easy-to-understand code samples that are going to stay with you for long.

Seems interesting? So let the ride begin.

The Asynchronous World of Android

We don’t generally give it a thought, but if you do, you will be amazed to find that the world of Android is asynchronous in so many ways. If you need to read/write data to the disk, you will need to wait for some time before the operation is complete. It can’t happen instantly, right?

The situation is similar when you are making a network call to retrieve some data from some remote server. The network call is not synchronous. It will take some time, from a few milliseconds to a few seconds, depending on your network quality, server load, etc. to deliver the results back to you.

If you give it some more thought, you will realize that the whole user input mechanism in Android is asynchronous in nature. The device is continuously waiting for user inputs like touch, drag, swipe, pinch, etc. and it reacts to those inputs accordingly.

Makes sense so far, let’s move ahead then.

Let’s Start Thinking Reactive

As you have already realized — from database transactions, file operations, network calls to heavy computation, user inputs, push notifications, almost everything in the Android world is asynchronous in nature.

So, why are we working so hard in modelling our apps in a synchronous fashion, where the world in which they will eventually run is heavily asynchronous in nature?

Isn’t it a question we should ask ourselves first before diving into writing our apps? Shouldn’t we think of using a better approach that can make our development lives slightly easier?

So, let’s start thinking in a reactive way. I know, it might be quite difficult to make such a huge paradigm shift all of a sudden as most of us have been thinking and writing code in an imperative way for most of our lives. But we all need to make a start somewhere, right?

Reactive programming is not difficult, it is just different.

In my opinion, reactive programming is actually easier and immensely powerful if you know how to make proper use of it. If it seems difficult to you, it simply means that you have not got the concepts right yet. But you always can, don’t worry.

It can take time, maybe a lot of time, but once you get it, you will surely fall in love with its beauty and power.

So, consider focusing on understanding the core concepts and fundamentals first, try to think of scenarios where you can make the best use of them and whenever you are stuck, remind yourself that you might need to change the way you are thinking or approaching the problem.

Reactive programming is fundamentally different from Imperative programming.

Reactive programming is fundamentally different from the Imperative programming we have been doing for long. But taking the effort to make such a radical shift is really worth it. You will see for yourself how easy and fun it becomes once you start getting better at it.

Recommended Reading

The Benefits of Taking The Reactive Road

By now you might have already guessed the power, reactive programming can put into your hands. So now, let’s discuss some of the immediate benefits you can enjoy by introducing RxJava into your Android project.

Multithreading Like a Boss

Those who know it, know it well, how difficult multi-threading can sometimes get in Java. There are so many ways in which you can get it screwed up.

But RxJava can make it insanely easy and convenient to perform complex threading operations, maintaining synchronization and getting the results delivered back to your friendly UI thread.

Eliminating The Dreaded “Callback Hell”

When you need to perform multiple asynchronous operations and each of them depends on the result of the previous operation, you unknowingly start creating a callback hell in your code.

It becomes extremely difficult to understand and maintain code bases like that. With reactive programming, you can completely eliminate this scenario and write clean, concise and maintainable code.

Error Handling Becomes a Breeze

It’s not always sunshine and rainbows when you are interacting with real-world asynchronous sources of data, like the network, databases, files, etc.

They might sometimes fail and when they do, you need to have a robust error handling mechanism in place to tackle various critical scenarios with ease.

An Arsenal of Operators

The real power of reactive programming comes from the huge arsenal of well-tested and powerful operators which can help you perform several common (and not-so-common) tasks with ease. There are lots (and lots) of operators available in the inventory and this is exactly where most developers get overwhelmed.

You need to start by understanding some of the basic operators first and then slowly learn more as you need them. You don’t need to learn everything today.

Less Code, Less Mistakes, Less Bugs

When you are writing code in a reactive way, your code automatically becomes more readable, understandable and maintainable. You will find yourself writing significantly less code, being less frustrated, making way less mistakes and writing more robust and stable code.

Enjoy Cross-Platform Support

Reactive programming is a concept or a programming paradigm that is available across several languages like Java, JavaScript, Python, Swift, Kotlin, C++ and many more.

It doesn’t matter if you are working on the mobile platform, web or backend. The knowledge you gain once can help you write better code everywhere.

These are just some of the many benefits of taking the reactive approach. I will leave it to you to discover more as you start your new journey of reactive programming.

Let’s Talk About RxJava Now

To put it in the simplest words possible, reactive programming is a paradigm where the consumer reacts to data as and when they come to it. It is a concept and ReactiveX is basically the god project which aims to provide implementations of this concept across multiple programming languages.

As they describe,

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

RxJava is just the implementation of this concept for the Java programming language. Recently, they released a major update where the entire library was rewritten from scratch on top of the Reactive Streams specification.

We will completely be focussing on RxJava 2 on this article. For the record, whenever I mention RxJava in this article, it automatically refers to RxJava 2.

The 3 O’s of RxJava

Let’s dive into the core concepts of RxJava now — Observable, Observer and Operator.

In the reactive world, you should consider everything as a stream. Something would produce/emit a stream of data for something else to modify or consume. But if you look closely, this is actually not a new concept by any means. This is just the Observer design pattern in action, but infinitely more powerful.

Examples of streams of data can be sensor data changes, location updates, touch events in the UI, push notifications and so much more.

Recommended Reading

Observable

In simple words, something that can be observed (observe + able) is an Observable. It basically represents the source of data that you are interested in and want to observe.

Let’s try to understand this better with a real-world example. Suppose you have attended a conference. The speaker there is someone who you are interested in listening to. You can consider this speaker as an “Observable” who is continuously producing streams of information for you (and others) to consume.

Hot vs Cold Observable

Now as you have grasped the basic idea of what an Observable actually is, let’s dig deeper.

We can have Observables which emit items only when someone subscribes to it. Like the speaker, in our imaginary conference will not likely to talk alone until and unless there is someone in the room listening to him. This can be considered as a Cold Observable.

Similarly, we can also have Observables which can emit items even if no one is subscribed to it. Like, the speaker can be very desperate and continue giving his presentation even if there is no one in the room listening to him. Attendees can join in later one by one and start listening to him from that point onwards. This can be considered as a Hot Observable.

In the Android world, a cold Observable can be a network call which doesn’t fetch (or emit) data all by itself if no one is subscribed to it. Only if someone is interested in this event and subscribes to it, the Observable makes the network call, fetches the data and emits it to the interested subscriber. These emissions are not shared across multiple subscribers.

A hot Observable, on the other hand, can be the location update event stream. Location updates will still continue to happen, even if no one is interested in it. If a subscriber eventually shows interest in these updates and considers subscribing, then it will start getting updates that are emitted from the point of its subscription.

Get, Set, Code

An example of an Observable you would typically use will be something like this,

Observable<Movie> movieObservable = remoteService.getMovies();

Here, the Observable can emit Movie objects retrieved from some remote data source. There can be a single item, multiple items or no items emitted by this Observable. If the Observable is unable to fetch data, it will signal an error.

If you need to create an Observable all by yourself, here is how you can do it,

Observable<Movie> movieObservable = Observable.create(emitter -> {
try {
// Fetches Movie objects from the network, database, etc.
List<Movie> movies = getMovies();
for (Movie movie : movies) {
emitter.onNext(movie);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
});

We will talk about the onNext(), onComplete() and onError() methods later in detail. Here are some convenience methods for you to create Observables quickly,

Check out this page for a complete list of all the ways in which you can create an Observable.

So, by now you should have a basic idea of why you should start building your apps in the reactive way. We have also discussed about the concept of Observables and how you can create and use them.

This is just the start of our journey on understanding and mastering reactive programming for Android development. We will continue with more amazing stuff in the next part of the series. So, stay tuned. You can also follow me on Twitter to get updates when the next part is live.

This article was originally published on TechBeacon.

Next Part Of The Series

--

--

Design-focused Engineer | Android Developer | Open-Source Enthusiast | Part-time Blogger | Catch him at https://about.me/aritra.roy