Android and RxJava: Using a Single

In the last article, we took a basic look at RxJava, and used Observable.create() to create our Observable. We also setup an Observer that listens for data. In this blog post, we’ll talk about Single.just() and how it differs from Observable.just(). Let’s get started!

Let’s make some changes to our MainActivity:

What exactly is going on here? First, we changed firstNames to firstName. As you can tell, we only pass in one name, “Daniel.” But the important thing to note is that Observable.just() got changed to Single.just(). What’s the difference? The difference lies with the subscriber. If you look at the observer variable, you’ll noticed a few things changed. First of all, we only have 2 callback methods: onSuccess and onError.

Before we had methods like onNext(). With Single, we only get these 2 methods: onSuccess and onError. That’s it. If it’s successful, the name “Daniel” will go to onSuccess(). If for some reason there is an error, onError() will be called.

With Single, we simply care about the 1 result, or the 1 error, that’s all. Single cannot accept multiple names like Mel, Daniel or Nathan. Just one name, like Daniel.

However, with Single, you can pass a list of names, but the names will be in List<String> instead of just String.

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.

1 year ago

findViewById() in Kotlin

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

1 year 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 year ago