Crunching RxAndroid — Intro

Roberto Orgiu
Crunching RxAndroid
2 min readFeb 23, 2015

--

Learning Reactive Programming the easy way

A few months ago, I was reading this incredibly amazing series of articles from Dan Lew and, after a bit of time, I decided to try this framework by myself, sharing the bit of knowledge I gain every day.

Let’s get started

First of all, we have to set up a new Android project, adding RxAndroid as dependency in the build script

compile ‘io.reactivex:rxandroid:0.24.0'

In case you want to skip this initial part, feel free to download the base project from GitHub.

Crunching the code

At first sight, Reactive Programming can be tricky but, after a little while, it’s pretty nice seeing all the magic you can do with virtually no effort. Let’s dive into the code, then!

In this part, we will face two basilar components of this paradigm: Observables and Subscribers. The first ones will emit any number of items to all the Subscribers that are listening to the changes.

The main idea of the beginning is to have an Observable emitting the string Hello, World and then terminating the execution:

Observable.OnSubscribe observableAction = new Observable.OnSubscribe<String>() {
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext(“Hello, World!”);
subscriber.onCompleted();
}
};
Observable<String> observable = Observable.create(observableAction);

The next step is to create a couple of Subscribers: one will change the value in a TextView to a string received as parameter, the other will instead create a Toast and display it.

Subscriber<String> textViewSubscriber = new Subscriber<String>() {
public void onCompleted() {}
public void onError(Throwable e) {}
public void onNext(String s) {
txtPart1.setText(s);
}
};
Subscriber<String> toastSubscriber = new Subscriber<String>() {
public void onCompleted() {}
public void onError(Throwable e) {}
public void onNext(String s) {
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
};

Finally, we just have to wire the logic: we need to make our Observable return its value on the main thread and then add the Subscribers to it, so that the object can start emitting items when needed (that means when someone is observing).

The reason behind the need of observing the main thread is that we want to act on the Android UI… and for doing so you have to be on the proper thread!

observable.observeOn(AndroidSchedulers.mainThread());
observable.subscribe(textViewSubscriber);
observable.subscribe(toastSubscriber);

If you want to take a deeper look to the code (there isn’t much more, though), you can download the zip from this link or clone the repo, that will be updated with the new discoveries.

Stay tuned for scenes from the next episode.

--

--