Party tricks with RxJava, RxAndroid & Retrolambda

All the cool kids are doing it, why aren’t you?

César Ferreira
The Startup

--

Users expect real time data. They want their tweets now. Their order confirmed now. As a developer, you demand fire-and-forget messaging. You really don’t want to be blocked waiting for a result… You want to have the result pushed to you when it is ready, whenever that is. Even better, when working with big result sets, you want to receive individual results as they are ready because you don’t want to wait for the entire set to be processed before you see the first item on that list. Developers have lots of tools to push data, that’s easy. Developers need tools to react to pushed data.

Let there be light… even better… Reactive Extensions!

Described as “a library for composing asynchronous and event-based programs by using observable sequences” it is very well suited for introducing and managing concurrency for the purpose of offloading. That is, performing a given set of work concurrently to free up the current thread (usually the UI thread). A very popular use of this is to maintain a responsive UI, which is essential for a great mobile user experience!

I’ve been assembling a few usage examples as I learn how to use them in the last couple of months and I’ve decided to share them…

Just remember:

The basic building blocks of reactive code are Observables and Subscribers. An Observable emits items; a Subscriber consumes those items.

Import your dependencies:

…and configure retrolambda:

https://github.com/orfjackal/retrolambda

UPDATE: I’ve written a small tutorial about a super easy way to configure retrolambda https://medium.com/@cesarmcferreira/retrolambda-on-android-191cc8151f85

Fire up your IDE and let’s try’em out!

Some people assume that, because RxJava is all about “asynchronous sequences”, everything will happen on different threads by default, but that’s not the case so don’t forget to define both .observeOn() and .subscribeOn(). The first defines the thread in which the Observer will be subscribed (thread where the data will be received upon completion) and the latter produces a new Observable which will cause your subscription to occur on a thread retrieved from the specified scheduler instead of the thread from which subscribe() is called (android’s main thread, the UI thread).

Bonus: Retrofit

… + RxJava + RxAndroid + Retrolambda

Let’s see them all in action:

Pretty sweet right?

Here’s a few extra links with cool information:

If you have suggestions you want to see added ask away or create a pull request to this gist https://gist.github.com/cesarferreira/510aa2456dc0879f559f

Hit me up on @cesarmcferreira if you have any questions☺

Published in Startups, Wanderlust, and Life Hacking

-

--

--

César Ferreira
The Startup

Senior Android Developer, currently working as a Tech Lead @GlueHome. More on me @ https://cesarferreira.com