RxJava + Android
In the previous post we talked about Lambdas on Android.
In this article, we are going to explore the amazing world of Reactive Programming. This is a combination of the best ideas from the Observer
pattern, the Iterator
pattern, and functional programming. Chances are you've heard of RxJava. RxJava is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences.
Why Consider RxJava?
As a developer you don’t have to worry too much about the details of how to perform operations that should occur on different threads. RxJava simplifies development because it raises the level of abstraction around threading. If you have done threading, it can be a nightmare. If not correctly implemented, can cause some of the most difficult bugs to debug and fix.
Problem.
So let’s say you want to compare if two passwords match. We’d need to implement .addTextChangedListener()
to listen for any changes on the EditText
then compare if the passwords match.
This how the above would look.
Let’s Go Rx.
1. The Observable. We’ll implement an Observable
which will emit changes. An Observable is the stream abstraction in RxJava. It is similar to an Iterator in that, given a sequence, it iterates through and produces those items in an orderly fashion.
Observable passwordObservable = RxTextView.textChanges(mPasswordEditText);
2. Subscription The Subscribe
operator is the glue that connects an observer to an Observable. In order for an observer to see the items being emitted by an Observable. In English, the Subscription will replace .addTextChangedListener()
.
- .observeOn()
: This will allow us to specify where we want us to run the operation, in this case main thread.
- .debounce()
: This will enable to wait for x time before comparing items.
- .doOnNext()
: We'll use this to hide the error if the password is correct. Putting it all together
This combines the latest item emitted by each Observable and helps us compare the observables.
If the passwords match, the error message on confirm password is removed & register button is enabled.
Final Result
The source code is available on GitHub
In the next series we’ll implement Realm… Go forth an Rx-ify
the world.