Rxjs 一个 Observable 馈入另一个 [英] Rxjs One Observable Feeding into Another

查看:26
本文介绍了Rxjs 一个 Observable 馈入另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组看起来相当笨重的代码,其中来自一个 observable 的数据被馈送到另一个,如下所示:

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 });
   });

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

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.

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

以下是一些您可以使用的表现不同的平面运算符:

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

  • flatMap/mergeMap - 立即为任何源项创建一个 Observable,所有先前的 Observable 都保持活动状态
  • concatMap - 在创建下一个 Observable 之前等待前一个 Observable 完成
  • switchMap - 对于任何源项,完成前一个 Observable 并立即创建下一个
  • exhaustMap - 映射到内部 observable,忽略其他值直到该 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 - map to inner observable, ignore other values until that observable completes

这篇关于Rxjs 一个 Observable 馈入另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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