Switching

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

If, for example, we have a process that emits nine strings, and it delays each string emission randomly from 0 to 2,000 milliseconds (emulating an intense calculation), this can be demonstrated as follows:

import io.reactivex.rxjava3.core.Observable;import java.util.concurrent.ThreadLocalRandom;import java.util.concurrent.TimeUnit ...

Get Learning RxJava - Second Edition 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.