1

I have a list of observables that needs to invoke APIs synchronously. The APIs fails for asynchronous operation. Hence an observable needs to wait for the previous observable to complete before executing, I have written a recursive solution as shown below, is there a better way to do it.

 private myMethod(params) {
    let paramsCopy = params.slice();
    let param = paramsCopy.shift();
    if (param) {
     let resource: ResourceModel= param.resource;
     return resource.doPost(JSON.stringify(param.data))
                    .pipe(mergeMap(res => {return myMethod(paramsCopy)})
                    ,catchError((err) => handleError()));
    } else { 
       return //completed actions;
    }
 } 
Sasi Kumar M
  • 2,440
  • 1
  • 23
  • 23
  • https://blog.angularindepth.com/practical-rxjs-in-the-wild-requests-with-concatmap-vs-mergemap-vs-forkjoin-11e5b2efe293 – Vikas Jun 24 '19 at 12:39
  • You can use the `switchMap` operator. Take a look [link](https://stackoverflow.com/a/51057338/8712609). – riorudo Jun 24 '19 at 12:41
  • 1
    Use `concatMap - waits for the previous Observable to complete before creating the next one` – Vikas Jun 24 '19 at 12:48

2 Answers2

1
myService.get1().pipe(
  switchMap(responseOfGet1 => myService.get2())
).subscribe(responseOfGet2 => { ... });

Documentation

1

You can use concat(observables: ...*): Observable. With this, the observable will wait for the other to complete. Please refer the link - https://www.learnrxjs.io/operators/combination/concat.html

Vinodini S
  • 38
  • 4