【发布时间】:2019-08-30 21:39:37
【问题描述】:
想象一下,我有一个 observable 给我巧克力饼干,但我不想吃白色的。但是由于我是盲人,所以我必须将它们交给服务来确定给定的 cookie 是否是白色的。但我没有马上得到答案。我宁愿得到另一个 observable。
所以这是我想出的代码,但我真的不喜欢它,我认为应该有一个更简单、更优雅的解决方案:
// pipe the observable
chocolateCookieObservable$.pipe(
// use a switchMap to create a new stream containing combineLatest which combines...
switchMap((chocolateCookie: ChocolateCookie) => combineLatest(
// an artificially created stream with exactly one cookie...
of(chocolateCookie),
// and the answer (also an observable) of my cookie service
this.chocolateCookieService
.isChocolateCookieWithWhiteChocolate(chocolateCookie),
// so I get an observable to an array containing those two things
)),
// filtering the resulting observable array by the information contained in
// the array (is the cookie white)?
filter(([chocolateCookie, isWhite]: [ChocolateCookie, boolean]) => !isWhite),
// mapping the array so that I can throw away the boolean again, ending up
// with only the now filtered cookies and nothing more
map(([chocolateCookie]: [ChocolateCookie, boolean]) => chocolateCookie),
).subscribe((chocolateCookie: ChocolateCookie) => {
this.eat(chocolateCookie);
}
虽然这确实有效并且在某种程度上是合理的,但如果您必须将更多的内容封装在一起,那真的会变得非常混乱。有没有办法直接过滤 observable 或映射它,这样我就可以在不使用那个奇怪的 combineLatest-of 组合的情况下获得我需要的信息?
【问题讨论】:
标签: javascript angular typescript rxjs