Sasi Kumar M
Sasi Kumar M

Reputation: 2630

How to make observable wait for the previous observable to complete

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

Upvotes: 1

Views: 123

Answers (2)

Vinodini S
Vinodini S

Reputation: 38

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

Upvotes: 1

user4676340
user4676340

Reputation:

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

Documentation

Upvotes: 1

Related Questions