Android and RxJava: Getting Started

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:

Logcat, found at the bottom of Android Studio.

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.

About the author

Daniel Malone
Bringing more than a decade of software engineering experience, Daniel Malone is Editor at androidEveryday. An Austin native, Daniel is often found reading technical books, blogging and creating YouTube tutorials. When not working, he likes to listen to pop hits on Google Play Music.

Android RecyclerView Tutorial (Part 1)

  • Most apps contain lists of data using RecyclerView.
  • In this tutorial, use ConstraintLayout and Kotlin to display a list of data.

3 weeks ago

findViewById() in Kotlin

  • As you may have discovered, findViewByid() is no longer needed.
  • Kotlin adds the ability to directly access Views.

1 month ago

Android Architecture Components Tutorial: ViewModel + LiveData

  • Use Kotlin to build a basic Android app using Android Architecture Components.
  • As part of Jetpack, LiveData and ViewModel support a MVVM app architecture.

1 month ago