0

I have an array of object and I want to loop over the array and call the service for each element, BUT for every element, I want to call the next element only when the current call is done with success, unless block the rest.

    onUpload(items: MyItem[]) {
      items.forEach(i => {
        myService.doSomething(i).subscribe(response => {
          // do something with the success item i
          // do the next call for the next item 
        }, error => {
          // handle the error
        })
      })

     }

Is there to call Observables in sequence mode not parallel?

3 Answers3

2

Use from to emit values from an array and then contactMap to sequentially execute observables

import { from } from 'rxjs';
import { concatMap } from 'rxjs/operators';

onUpload(items: MyItem[]) {
  from(items)
    .pipe(
       concatMap(item => myService.doSomething(i))
    )
    .subscribe(response => {/* do something with response */});
}
1

Use concat from rxjs. Documentation is here https://www.learnrxjs.io/learn-rxjs/operators/combination/concat.

Code looks like:

onUpload(items: MyItem[]) {
  const observableArray = items.map(i => myService.doSomething(i));
  concat(...observableArray).subscribe(
    () => { /* Some logic */ },
    (err) => { /* Some logic */ },
  );
}
Dmitrii Makarov
  • 757
  • 3
  • 11
0

I think it will more gracefull

onUpload(items: MyItem[]) {
  from(items)
  .pipe(mergeMap((item) => myService.doSomething(item)))
  .subscribe(
    () => console.log(finish),
    (err) => console.log('error happens', err),
  );
}