Home Application-development RxJava Essentials

RxJava Essentials

By Ivan Morgillo
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book

RxJava—Reactive Extensions for the JVM—is a library for composing asynchronous and event-based programs using Observable sequences for the Java VM, which will help you beat Android platform limitations to create astonishing Android apps.

Starting with some quick background information on the Rx .NET library, this book quickly moves on to your first example. You will understand Observables and learn to filter, transform, or merge them in detail. Next, you will learn how to get rid of Threads, AsyncTasks, and Handlers with Schedulers to create a smooth user experience. Develop an easy, ready-to-go approach to REST API communications and enrich your skills by working with new challenging examples.

By the end of the book, you will have explored the reactive programming world and will have created your first Android app without having to think about threading, networking, concurrency, and collection management.

The images have been taken from http://reactivex.io/ which is licensed under a Create Commons 3.0 Attribution license (https://creativecommons.org/licenses/by/4.0/)

Publication date:
May 2015
Publisher
Packt
Pages
132
ISBN
9781784399108

 

Chapter 1. RX – from .NET to RxJava

Reactive programming is a programming paradigm based on the concept of an asynchronous data flow. A data flow is like a river: it can be observed, filtered, manipulated, or merged with a second flow to create a new flow for a new consumer.

A key concept of reactive programming is events. Events can be awaited, can trigger procedures, and can trigger other events. Events are the only proper way to map our real world to our software: we open a window if it's too hot inside. In the same way, we want the Total cell to update when we change some values in our spreadsheet (the propagation of the changes) or our robot to turn around the moment it reaches the wall (reaction to events).

Nowadays, one of the most common scenarios for reactive programming is UIs: we have mobile apps that have to react to network calls, user touch input, and system alerts. In this world, software has to be event-driven and reactive because real life is event-driven.

 

Microsoft Reactive Extensions


Functional reactive programming is an idea from the late 90s that inspired Erik Meijer, a computer scientist at Microsoft, to design and develop the Microsoft Rx library.

Rx is a reactive extension for Microsoft .NET. Rx provides an easy way to create asynchronous, event-driven programs using Observable sequences. A developer can model an asynchronous data stream using Observables, query the Observables using LINQ syntax, and easily manage concurrency with Schedulers.

Rx makes well-known concepts, such as the push approach, easy to implement and consume. In a reactive world, we can't just wait for a function result, a network call, or a database query to return and pretend that the user won't notice or even complain about it. Every moment we wait for something, we lose the opportunity to do other things in parallel, provide a better user experience, and free our software from the chains of sequential, blocking programming.

.NET Observable relates to .NET Enumerable according to the following table:

.NET Observable

Single return value

Multiple return values

Pull/Synchronous/Interactive

T

IEnumerable<T>

Push/Asynchronous/Reactive

Task<T>

IObservable<T>

The push approach reverses the problem: instead of asking for a result and waiting, the developer simply asks for a result and gets notified when the result is available. The developer provides a clear sequence of reactions to the events that are going to happen. For every event, the developer provides a reaction; for example, the user is asked to log in and submit a form with his username and password. The application executes the network call for the login and states what is going to happen:

  • Show a success message and store the user's profile

  • Show an error message

As you can see with the push approach, the developer doesn't wait for the result. He will be notified when the result arrives. In the meantime, he can do whatever he wants:

  • Show a progress dialog

  • Store the username and password for future logins

  • Preload something he knows would take some time the moment the login succeeds

 

Landing in the Java world – Netflix RxJava


In 2012, at Netflix, they started to realize that their architecture was having a hard time to properly adapt to the amount of users they had. They decided to redesign their architecture to reduce the number of REST calls. Instead of having dozens of REST calls and letting the client process the data as needed, they decided to create a single optimized REST call based on the clients' needs.

To achieve this goal, they decided to go reactive, and they started to port .NET Rx to the JVM. They didn't want to target just Java; they decided to target the JVM instead, having the possibility to provide a new tool for every JVM language on the market: Java, Closure, Groovy, Scala, and so on.

With a post on the Netflix tech blog in February 2013, Ben Christensen and Jafar Husain showed RxJava to the world for the first time.

The key concepts were:

  • Easy concurrency to better use their server's power

  • Easy conditional asynchronous execution

  • A proper way to escape the callback hell

  • A reactive approach

As for .NET, RxJava Observable is the push equivalent of Iterable, which is pull. The pull approach is a block-and-wait approach: the consumer pulls values from the source, blocking the thread until the producer provides new values.

The push approach works on subscription and reaction: the consumer subscribes to new values' emissions; the producer pushes these new values when they are available, and notifies the consumer. At this point, the consumer, well, consumes them. The push approach is clearly more flexible, because from a logical and practical point of view, the developer can simply ignore if the data he needs comes synchronously or asynchronously; his code will still work.

What's different in RxJava

From a pure Java point of view, the RxJava Observable class extends the classic Gang of Four Observer pattern concept.

It adds three missing abilities:

  • The producer can now signal that there is no more data available: the onCompleted() event

  • The producer can now signal that an error occurred: the onError() event

  • RxJava Observables can be composed instead of nested, saving the developer from the callback hell

Observables and Iterables share a similar API; lots of operations that we can perform on Iterable can be performed on Observable too. Of course, due to the "flow" nature of Observables, we don't have equivalents for methods such as Iterable.remove().

Pattern

Single return value

Multiple return values

Synchronous

T getData()

Iterable<T> getData()

Asynchronous

Future<T> getData()

Observable<T> getData()

From a semantic point of view, RxJava is .NET Rx. From a syntactical point of view, Netflix takes care of porting every Rx method, keeping in mind Java code conventions and basic patterns.

 

Summary


In this chapter, we took the initial steps into the reactive world. We learned how Rx was born, from Microsoft .NET to Netflix RxJava. We learned the similarities and differences of the reactive approach compared with the classic approach.

In the next chapter, we will learn what Observables are, and how we can create them to bring reactive programming into our daily coding life.

About the Author
  • Ivan Morgillo

    Ivan Morgillo is a computer engineer, a conference speaker, and a community organizer. He is passionate about programming and embedded systems—from DIY domotics to Android devices.

    He is cofounder of Alter Ego Solutions, a mobile development consulting company.

    He is also the author of RxJava Essentials, by Packt Publishing and Grokking Rx, by Manning Publications.

    Browse publications by this author
Latest Reviews (10 reviews total)
Good book, but I think you missing more code and real world examples. Some concepts presented in book still vague for me after book reading.
RxJava Essentials
Unlock this book and the full library FREE for 7 days
Start now