TimS
TimS

Reputation: 1113

Conditionally choose observable in RxJS

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

Upvotes: 3

Views: 1100

Answers (1)

user3743222
user3743222

Reputation: 18665

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.

Upvotes: 1

Related Questions