【问题标题】:concatMap array of observablesconcatMap 可观察对象数组
【发布时间】:2020-11-20 06:42:00
【问题描述】:

我有一组要按顺序执行的可观察对象,即等待一个请求在下一个请求之前完成。

如果我使用 forkJoin,请求是并行执行的,我可以像这样使用它,

forkjoin(arrayOfObservables)

使用 concatMap 和 observables 数组的等效方法是什么。我想要类似的东西

concatMap(arrayOfObservables)

例子:

  booleanQuestion$ = (question) => {
    return this.assessmentService
      .createBooleanQuestion(this.testId, question)
      .pipe(
        tap(
          (res) => {
            this.questionsCreated += 1;
            this.progress =
              (this.questionsCreated / this.questions.length) * 100;
          },
          (err) => console.log(err)
        )
      );
  };


  pushBooleanQuestions(): Array<Observable<any>> {
    const booleanQuestions$ = [];
    this.booleanQuestions.forEach((questionObj) => {
      questionObj.order = this.elements.findIndex(
        (element) => element.component === questionObj.component
      );
      delete questionObj.component;
      booleanQuestions$.push(this.booleanQuestion$(questionObj));
    });
    return booleanQuestions$;
  }



  let allQuestions = this.pushBooleanQuestions()
        .concat(this.pushSubjectiveQuestions())
        .concat(this.pushObjectiveQuestions());
  this.questionCreation$ = forkJoin(allQuestions);

我想订阅 this.questionCreation$。它应该使用 concatMap 而不是 forkJoin。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    使用简单的concat 进行数组解构:

    const a$ = of('one').pipe(delay(1000))
    const b$ = of('two').pipe(delay(2000));
    const c$ = of('three').pipe(delay(1000));
    
    const arrayOfObservables = [a$, b$, c$];
    
    concat(...arrayOfObservables).subscribe(x => console.log(x));
    
    // result: 'one' after 1s, 'two' after 2s and 'three' after 1s (4s total, not in parallel)
    

    现场演示: https://stackblitz.com/edit/concat-rx?file=index.ts

    【讨论】:

    • 你先生,是救命稻草!
    【解决方案2】:

    如果您想使用 concatMap 运算符完成相同的操作,您可以这样做:

    from(arrayOfObservables).pipe(concatMap((observable) => observable))
    .subscribe(x => console.log(x));
    

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2018-12-16
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多