Rxjs一个可观察的馈入另一个 [英] Rxjs One Observable Feeding into Another

查看:81
本文介绍了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一个可观察的馈入另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆