RxJava in Action
Get an overview of how things work in RxJava.
We'll cover the following...
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. TheObservable
waits for an observer to subscribe to it, at which point it does some work and pushes data to itsObserver
. We intentionally abstract away the creation of thecarsObservable
here, and we’ll cover how to create anObservable
in the next chapter. For now, let’s assume the work that theObservable
will be doing is querying a REST API to get an ordered list of the top-selling cars. ...