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 ...