Rxjs一个可观察的馈入另一个

编程入门 行业动态 更新时间:2024-10-17 15:21:08
本文介绍了Rxjs一个可观察的馈入另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一组看起来很笨拙的代码,其中来自一个可观察到的数据被馈送到另一个,例如:

I have a rather clunky looking set of code where the data from one observable is feed into another, like such:

let source = this.myService.getFoo() .subscribe(result => { let source2 = this.myService.getMoo(result) .subscribe(result2 => { // do stuff }); });

我知道有多种方法可以组合和链接,但是我需要将源中的数据输入到source2中.订阅的嵌套看起来糟透了,我可以肯定,有更好的方法可以做到这一点.

I know that there are ways to combine and chain but I need data from source to be feed into source2. The nesting of subscribes looks terrible and I'm pretty certain there is a better way to do this.

谢谢!

推荐答案

要将一个Observable发出的项目转换为另一个Observable,您可能要使用flatMap运算符.它创建一个内部Observable并将其结果平放到外部流.

For transforming items emitted by an Observable into another Observable, you probably want to use the flatMap operator. It creates an inner Observable and flats its result to the outer stream.

let source = this.myService.getFoo() .flatMap(result => this.myService.getMoo(result)) .subscribe(result2 => { // do stuff });

您可以使用一些平整的运算符,它们的行为有所不同:

Here are some flat operators you can use that behave differently:

  • flatMap/mergeMap -为任何源项目立即创建一个Observable,所有先前的Observable均保持活动状态
  • concatMap -等待上一个Observable完成,然后再创建下一个
  • switchMap -对于任何源项目,完成上一个Observable并立即创建下一个
  • exhaustMap -在前一个Observable未完成时,源项目将被忽略
  • flatMap/mergeMap - creates an Observable immediately for any source item, all previous Observables are kept alive
  • concatMap - waits for the previous Observable to complete before creating the next one
  • switchMap - for any source item, completes the previous Observable and immediately creates the next one
  • exhaustMap - source items are ignored while the previous Observable is not completed

更多推荐

Rxjs一个可观察的馈入另一个

本文发布于:2023-11-27 23:28:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640031.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rxjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!