O'Reilly logo

Reactive Android Programming by Tadas Subonis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

SwitchMap

.switchMap() is a very close cousin of .flatMap(). The difference between them is that .flatMap() will return wait to return all of the elements from the Observables that were created inside .flatMap(), while .switchMap() will only return elements from the newest Observables that were created from the newest values.

The easiest way to explain this is by example. First, let's take a look at how .flatMap() will work with this:

Observable.interval(3, TimeUnit.SECONDS)        .take(2)        .flatMap(x -> Observable.interval(1, TimeUnit.SECONDS)                .map(i -> x + "A" + i)                .take(5)        )        .subscribe(item -> log("flatMap", item));

This will basically produce the two sets of items that will be numbered from zero to four. In total, there will be 10 items printed ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required