/** * Returns a new Observable by applying a function that you supply to each item emitted by the source * Observable that returns an Observable, and then emitting the items emitted by the most recently emitted * of these Observables. * <p> * <img width="640" height="350" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchMap.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchMap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param func * a function that, when applied to an item emitted by the source Observable, returns an * Observable * @return an Observable that emits the items emitted by the Observable returned from applying {@code func} to the most recently emitted item emitted by the source Observable * @see <a href="https://github.com/Netflix/RxJava/wiki/Transforming-Observables#switchmap">RxJava wiki: switchMap</a> */ public final <R> Observable<R> switchMap(Func1<? super T, ? extends Observable<? extends R>> func) { return switchOnNext(map(func)); }
@Test public void sample_52() throws Exception { Observable<String> alice = speak( "To be, or not to be: that is the question", 110); Observable<String> bob = speak( "Though this be madness, yet there is method in't", 90); Observable<String> jane = speak( "There are more things in Heaven and Earth, " + "Horatio, than are dreamt of in your philosophy", 100); Random rnd = new Random(); Observable<Observable<String>> quotes = just( alice.map(w -> "Alice: " + w), bob.map(w -> "Bob: " + w), jane.map(w -> "Jane: " + w)) .flatMap(innerObs -> just(innerObs) .delay(rnd.nextInt(5), SECONDS)); Observable .switchOnNext(quotes) .subscribe(System.out::println); Sleeper.sleep(Duration.ofSeconds(10)); }