0

The switch documentation on github contains an example on how to use the command.

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');
});

I've tested the code at stackblitz but the output differs. Instead of

Next: 0
Next: 1
Next: 2
Next: 3
Next: 4
Completed 

the console logs

Next: 0
Next: 1
Next: 2
Next: 1
Next: 2
Next: 3
Next: 2
Next: 3
Next: 4
Completed

Can somebody explain?

user35934
  • 374
  • 2
  • 13

1 Answers1

0

Now I got it. The difference in the output comes from the fact that each inner observable sequence (created by the second call to range) won't be canceled as specified by the switch-operator since each observable sequence is emitted before the next sequence has been received, i.e. the observables in that sequence complete before switch has the chance to cancel those. But if I delay the emission only the elements of the

most recent inner observable sequence

is logged to the console:

var source = Rx.Observable
          .range(0, 3)
          .map(x =>  Rx.Observable.range(x, 3).delay(1))
          .switch();

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

Output:

Next: 2
Next: 3
Next: 4
Completed
user35934
  • 374
  • 2
  • 13