RxJava is a beast to learn, but it can be useful in just about any type of Android app. Today, let’s get started with RxJava basics, and how we can use it to build a simple app.
First, set up an empty Android project by following along with the written article or YouTube video.
Next, we need to add the dependencies to Gradle. RxJava is a library that exists on the internet, and Android Studio uses Gradle to download libraries that we can use in our app. Open build.gradle (Module: app) and add the following lines to the bottom of dependencies. (Click here for the complete build.gradle file.)
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
Next, open MainActivity.kt
and add the following line in the onCreate
method.
Now open Logcat in Android Studio and you should see the names above (Daniel, Mel, Nathan, etc.). That’s the basics. In real life, the names can come from a database in the cloud. It could be hosted on Google Cloud Platform or Amazon Web Services.
Let’s work with this further. Modify MainActivity.kt
to the following:

So what’s going on here? First, we set up a basic Observable
using Observable.just
. Next, we listen for firstNames
on line 20. Because Observable.just
emits all items within itself (“Daniel,” “Mel,”, etc.), we get each name passed from line 18 to line 20. Then, onNext
gets triggered for each name. onNext
passes the name as a parameter. In this case, a String
for each name.
If Observable.just
has 5 names, onNext
will be triggered 5 times. On line 26, we output each name to the console or Logcat. When all 5 names are finished, onComplete
is called. See the above screenshot for “complete!”
If there is a problem with anything, onError
will be triggered, and you can display an error message like a Snackbar
to the user.