rxandroid tutorial logo

RxAndroid Example – RxAndroid Tutorial #2

Vamsi Tallapudi Android 0 Comments

In this RxAndroid Example Tutorial, we will continue our previous topic on RxAndroid tutorial‘s Getting started where we discussed about the basics of RxJava 2 and RxAndroid and its uses.

Now, we are going to integrate the RxAndroid in our Project and write a simple Android Project which shows how to declare an Observable, Observer and subscribe to the Observable to receive the data.

rxandroid example tutorial logo

In this tutorial, we will be creating a simple android project where upon whenever we make a simple button click we would be making our observable emit some data and at the same time our observer subscribes and emits data which we can see via toast messages. So let’s get started.

Below image demonstrates what we would be targeting at the end of the RxAndroid Example Project:

RxAndroid Example Project final output demo gif

The complete code for this tutorial is given at the bottom of the article.

Methods which we will be using in this RxAndroid Example tutorial:

create()Creates a new Observable. This method is available from Observable class

onNext(T value) – Emits a value. This method is from Emitter interface.

onComplete() – called upon completion of Emission of data. This method is also from Emitter interface.

3 Simple Steps to demonstrate RxAndroid Example:

1. Creating an Observable

Lets begin by creating the Observable which will emit the data when user clicks a button. Here I am using Observable’s create() method.

As we know that now Android Studio 3 supports Java 8 features, let us use Lambda expressions which we discussed in our Previous Tutorial on Android Java 8 Features Integration.

Now the above code can be reduced to the following using Lambda Expressions:

2. Creating an Observer

Let us create an Observer and overriding all the required methods such as onSubscribe, onNext, onError, onComplete.

3. Subscribing Observer to Observable

This subscription can be done in a simple one liner:

Our completed RxAndroid Example Activity:

Now the finished MainActivity.java will look as follows:

Now we can see that whenever our button is clicked, Our Observable emits data and Observer subscribes and receives data.

The Complete code for this tutorial can be downloaded here:

In the next tutorial of RxAndroid, we will see different ways to create Observables and much more!