简体   繁体   中英

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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM