RxJava in Action

Get an overview of how things work in RxJava.

Sample RxJava code

Let’s take a look at some RxJava in action:

Press + to interact
Observable<Car> carsObservable = getBestSellingCarsObservable();
carsObservable.subscribeOn(Schedulers.io())
.filter(car -> car.type == Car.Type.ALL_ELECTRIC)
.filter(car -> car.price < 90000)
.map(car -> car.year + " " + car.make + " " + car.model)
.distinct()
.take(5)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateUi);

The above code will get the top 5 sub-$90,000 electric cars and then update the UI with that data.

There’s a lot going on here, so let’s see how it does this line-by-line:

  • Line 1: It all starts with our Observable, the source of our data. The Observable waits for an observer to subscribe to it, at which point it does some work and pushes data to its Observer. We intentionally abstract away the creation of the carsObservable here, and we’ll cover how to create an Observable in the next chapter. For now, let’s assume the work that the Observable will be doing is querying a REST API to get an ordered list of the top-selling cars. ...