首页 文章

用flatMap链接observables

提问于
浏览
1

我正在使用observables和flatMap运算符,我编写了一个方法,它调用并调用API并返回带有对象数组的observable . 基本上我需要的是让对象的数组,并处理每一个对象,毕竟,处理项目我想链的结果,使与我写的另一种方法,一个额外的API调用 . 以下代码可以满足我的需求:

this.apiService.getInformation('api-query', null).first().flatMap((apiData) => {
    return apiData;
  }).subscribe((dataObject) => {
    this.processService.processFirstCall(dataObject);
  }, null, () => {
    this.apiService.getInformation('another-query', null).first().subscribe((anotherQueryData) => {
      this.processService.processSecondCall(anotherQueryData);
    });
  });

但是从我的角度来看,这种方法并不是最优的,我想使用flatMap来链接这些调用,但如果我执行以下操作

this.apiService.getInformation('api-query', null).first().flatMap((apiData) => {
    return apiData;
  }).flatMap((dataObject) => {
    this.processService.processFirstCall(dataObject);
    return [dataObject];
  }).flatMap((value) => {
    return this.apiService.getInformation('another-api-query', null).first();
  }).subscribe((value) => {
    this.processService.processSecondCall(value);
  });

第二个API调用对apiData对象数组上的每个项执行一次 . 我知道我错过了或误解了什么 . 但是从这个线程的第二个答案Why do we need to use flatMap?我认为第二flatMap应该返回处理apiData,取而代之的是返回每个对数组对象的项目 . 我很感激你的帮助 .

谢谢 .

2 回答

  • 5

    你想要的是.do()运算符,而不是 flatMap() . flatMap() 将把事件转换为另一个事件,实质上是将它们链接起来 . .do() 只执行你指示它做的任何事情,以及事件中的每一次发射 .

    从您的代码中,有2个异步方法(调用api)和2个同步(processService) . 你想要做的是:

    • 调用第一个API(异步),等待结果

    • 处理结果(同步)

    • 调用第二个API(异步),等待结果返回

    • 处理结果(同步)

    因此,您的代码应该是:

    this.apiService.getInformation('api-query', null)//step1
        .first()
        .do((dataObject) => this.processFirstCall(dataObject))//step2
        .flatMap(() => this.apiService.getInformation('another-api-query', null))//step3
        .first()
        .do(value => this.processService.processSecondCall(value))//step4
        .subscribe((value) => {
            console.log(value);
        });
    

    我在评论中写了与上面列表相对应的步骤 . 我还清理了不必要的操作符(就像你的第一个 flatMap 有点多余) .

    此外,如果您要转换数据,则应使用.map()而不是 .do() . 我认为这是你与 .map().flatMap() 混淆的地方 .

  • 0

    我认为您遇到的问题是flatmap应该应用于可观察或承诺 . 在你的第二个代码示例,您在flatmap操作,然后将其传递给下面的flatmap职能范围内返回数据,而这些应该返回可观 . 例如:

    this.apiService.getInformation('api-query', null).first()
      .flatMap((dataObject) => {
        return this.processService.processFirstCall(dataObject);
      }).flatMap((value) => {
        return this.apiService.getInformation('another-api-query', null)
      }).subscribe((value) => {
        this.processService.processSecondCall(value);
      });
    

    有关进一步说明,请参阅this post .

相关问题