Mohit Harshan
Mohit Harshan

Reputation: 1986

concatMap array of observables

I have an array of observables which i want to execute in order, ie wait for one request to complete before the next.

If i use forkJoin, the requests are executed in parallel and i can use it like,

forkjoin(arrayOfObservables)

What is the equivalent way to use concatMap with array of observables. I want something like

concatMap(arrayOfObservables)

Example:

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

I want to subscribe to this.questionCreation$. It should be using concatMap instead of forkJoin.

Upvotes: 1

Views: 1738

Answers (2)

Srikanth Reddy
Srikanth Reddy

Reputation: 56

If you want to accomplish the same using concatMap operator, this is how you do it:

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

Upvotes: 0

Yevhenii Dovhaniuk
Yevhenii Dovhaniuk

Reputation: 1103

Use a simple concat with array destructuring:

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)

Live demo: https://stackblitz.com/edit/concat-rx?file=index.ts

Upvotes: 2

Related Questions