javascriptasynchronousrxjsrxjs-pipeable-operatorsconcatmap

Waiting for all async requests to complete with concatMap


assuming that there are multiple ajax requests that need to execute one by one sequentially, the next one should be called when the previous is done. I can achieve that by using the concatMap RxJs function, right? The question is how should I wait for all of the ajax requests passed to the concatMap to complete?

from(elementsList).pipe(concatMap((elem) => this.simpleFunc(elem)))).subscribe();

should be something like: waitForAll

or can I somehow use it in combination with forkJoin ?


Solution

  • You can use toArray to convert all the emissions to a single output.

    from(elementsList).pipe(
      concatMap((elem) => this.simpleFunc(elem)),
      toArray(),
    ).subscribe(console.log);
    

    If you do not care about the output and just want to react to the last emissions, then use last operator:

    from(elementsList).pipe(
      concatMap((elem) => this.simpleFunc(elem)),
      last(),
    ).subscribe(console.log);
    

    forkJoin performs all the operations in parallel, so it contradicts your requirements.