1

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

You sir, are a lifesaver!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.