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?

1

3 Answers 3

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 */});
}
Sign up to request clarification or add additional context in comments.

Comments

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 */ },
  );
}

Comments

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

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.