3

I would like to know how to create a new observable that will return one of two other observables based on if the first observable is empty (without calling the second observable by default). Eg:

// scenario 1
let obs1 = Observable.empty();
let obs2 = Observable.of([1,2,3]);
// This line doesn't work, but is essentially what I'm attempting to do
let obs3 = (obs1.isEmpty()) ? obs2 : obs1;
obs3.subscribe( i => console.log('Next: ', i));
// Next: 1
// Next: 2
// Next: 3
// Complete

// scenario 2
let obs1 = Observable.of([6,7,8]);
let obs2 = Observable.of([1,2,3]);
// This line doesn't work, but is essentially what I'm attempting to do
let obs3 = (obs1.isEmpty()) ? obs2 : obs1;
obs3.subscribe( i => console.log('Next: ', i));
// Next: 6
// Next: 7
// Next: 8
// Complete
TimS
  • 1,113
  • 7
  • 10

1 Answers1

1

You could try :

let obs3 = obs1.isEmpty().map(x => x? obs2 : obs1;)

Will check quickly now if that would work.

Yep, according to the doc, it should be fine, as isEmpty emits a boolean which is true if the observable is empty, so you can use that to pick up the observable you want.

user3743222
  • 18,345
  • 5
  • 69
  • 75
  • 1
    Shouldn't that be `flatMap/mergeMap`? – cartant Oct 26 '16 at 23:12
  • well he said `without calling the second observable by default`, so I assume `map` is the appropriate one. Now it is also true that given the examples, `flatMap` could be more appropriate. – user3743222 Oct 26 '16 at 23:50
  • Yes, I see what you mean; the question's use of "by default" is open to interpretation. – cartant Oct 26 '16 at 23:55