gpt4 book ai didi

javascript - 对于 RxJS 管道中的 Observables,是否有更简单、更优雅的解决方案?

转载 作者:搜寻专家 更新时间:2023-10-30 21:33:34 24 4
gpt4 key购买 nike

想象一下,我有一个 Observable 给我巧克力 cookies ,但我不想吃白色的。但由于我是盲人,我必须将它们交给一项服务来确定给定的 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);
}

虽然这确实有效并且有点合理,但如果您必须将更多的封装在彼此中,它真的会变得非常困惑。有没有什么方法可以直接过滤可观察对象或对其进行映射,这样我就可以在不使用那种奇怪的 combineLatest-of 组合的情况下获得我需要的信息?

最佳答案

您应该将其分解为多个语句。

在使用 Observables 实现复杂的异步工作流时,以这种方式工作将使您能够生成更具可读性、可维护性的代码。

重构后,您的代码将如下所示:

const isWhite$ = chocolateCookie$.pipe(
switchMap((chocolateCookie: ChocolateCookie) => this.chocolateCookieService.isChocolateCookieWithWhiteChocolate(chocolateCookie)),
);

chocolateCookie$.pipe(
withLatestFrom(isWhite$),
filter(([chocolateCookie, isWhite]: [ChocolateCookie, boolean]) => !isWhite),
map(([chocolateCookie]: [ChocolateCookie, boolean]) => chocolateCookie),
).subscribe((chocolateCookie: ChocolateCookie) => {
this.eat(chocolateCookie);
}

另外,请注意,您实际上不需要将“Observable”附加到变量名称的末尾,因为您已经在使用 $ 语法来表示该变量是一个 Observable。

关于javascript - 对于 RxJS 管道中的 Observables,是否有更简单、更优雅的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55595445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com