Conditionally select observable in RxJS

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

// 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
Run codeHide result
+3
source share
1 answer

You can try:

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

Will be checked quickly if this works.

Yes, according to doc , this should be good, because it isEmptyemits a boolean value that is true if the observable is empty, so you can use this to pick up the observable that you need.

+1
source

Source: https://habr.com/ru/post/1671935/


All Articles