Switch

convert an Observable that emits Observables into a single Observable that emits the items emitted by the most-recently-emitted of those Observables

Switch

Switch subscribes to an Observable that emits Observables. Each time it observes one of these emitted Observables, the Observable returned by Switch unsubscribes from the previously-emitted Observable begins emitting items from the latest Observable. Note that it will unsubscribe from the previously-emitted Observable when a new Observable is emitted from the source Observable, not when the new Observable emits an item. This means that items emitted by the previous Observable between the time the subsequent Observable is emitted and the time that subsequent Observable itself begins emitting items will be dropped (as with the yellow circle in the diagram above).

See Also

Language-Specific Information:

switch

RxGroovy implements this operator as switchOnNext. It does not by default operate on any particular Scheduler.

switch

RxJava implements this operator as switchOnNext. It does not by default operate on any particular Scheduler.

switch

RxJS implements this operator as switch

Sample Code

var source = Rx.Observable.range(0, 3)
    .select(function (x) { return Rx.Observable.range(x, 3); })
    .switch();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });
Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed

switch is found in each of the following distributions:

  • rx.js
  • rx.all.js
  • rx.all.compat.js
  • rx.compat.js
  • rx.lite.js
  • rx.lite.compat.js

RxPHP implements this operator as switchLatest.

Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.

Sample Code

//from https://github.com/ReactiveX/RxPHP/blob/master/demo/switch/switchLatest.php

$loop      = \React\EventLoop\Factory::create();
$scheduler = new \Rx\Scheduler\EventLoopScheduler($loop);

$source = Rx\Observable::range(0, 3)
    ->map(function ($x) {
        return \Rx\Observable::range($x, 3);
    })
    ->switchLatest();

$subscription = $source->subscribe($stdoutObserver, $scheduler);

$loop->run();

   
Next value: 0
Next value: 1
Next value: 2
Next value: 3
Next value: 4
Complete!