简体   繁体   English

有条件地选择RxJS中的observable

[英]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). 我想知道如何创建一个新的observable,它将返回两个其他observable中的一个,基于第一个observable是否为空(默认情况下不调用第二个observable)。 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. 是的,根据文档 ,它应该没问题,因为isEmpty发出一个布尔值,如果observable是空的,则为true,因此你可以使用它来获取你想要的observable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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