Android Reactive Programming with ReactiveX — Basic Examples with RxJava2, RxKotlin and RxAndroid

Laurence Liu
3 min readDec 12, 2018

Start coding with ReactiveX in Android

We could start coding after we have the basic concept of Reactive Programming and the libraries of ReactiveX. I will introduce the most commonly and widely use function in this part.

Before we start, remember the steps below. Making sure we follow those rules and execute them every time when we coding with RxJava. Once knowing the basic, it is easy to do some refactors to our code.

  1. Create Observable
  2. Create Observer
  3. Connect Observable and Observer with Subscribe

Adding Dependencies

We need to add the RxJava, RxKotlin and RxAndroid dependencies to our projects build.gradle and sync. ReactiveX update all the time, so make sure you get the newest one.

implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'

Following those steps

Create Observable

  • just(): Create an Observable that emits a particular item.

Create Observer

CreateSubscribe

  • subscribeOn(Schedulers.io()): This commands the Observable to run the task on a background thread.
  • observeOn(AndroidSchedulers.mainThread()): Observer will receive the data on Android UI thread so that developers can do things on UI thread when receive data.

Disposable

Disposable: This is an important component to avoid memory leak if we don’t need the Observer listen to Observable.

Moving back to the Observer we had created. There is a Disposable in the onSubscribe. We’ll create a global variable to save the status of Disposable and dispose it when we don’t need it.

We have to learn and comprehend the new syntax of RxJava, same as how we know hot the setOnClickListener or something else work.

Basic Examples in Android

I will give some examples with basic usage and simple data flow. This project use a single Activity with several Buttons and multiple DialogFragment with a TextView to show the process and result.

RxJava Basic

RxKotlin Basic

Operators

CompositeDisposable

CustomData

State Object

We have five examples so far. As we can see, there are a few steps need to done in every examples.

  • Create Observable
  • Create Observer
  • Create Subscribe
  • Do Operator (Optional)
  • Do Dispose (Optional)

It needs to take a lot of time to introduce each item of Observable and Operator. Fortunately, ReactiveX provides exhaustive document to help developers.

Although We have the basic concept, it still needs to do a lot of practices to be familiar with ReactiveX. Once knowing more, we could create what we want through the combination of these functions.

In next story, I will give some examples which are often used when we develop Apps in a practical situation.

--

--