Switching

In RxJava, there is a powerful operator called switchMap(). Its usage feels like flatMap(), but it has one important behavioral difference: it will emit from the latest Observable derived from the latest emission and dispose of any previous Observables that were processing. In other words, it allows you to cancel an emitting Observable and switch to a new one, preventing stale or redundant processing.

Say we have a process that emits nine strings, and it delays each string emission randomly from 0 to 2000 milliseconds. This is to emulate an intense calculation done to each one, as demonstrated here:

import io.reactivex.Observable;import java.util.concurrent.ThreadLocalRandom;import java.util.concurrent.TimeUnit;public class Launcher ...

Get Learning RxJava now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.