Wait for observable to complete

Viewed 49599

I have series of methods which are dependent on completion of other methods.

process1(data: string) : Observable<string> {
   this.dataservice.process(data).subscribe(
            (response) => {
                return response.data;
            }
        );
}

main(data: string) : string {

   var process1Data: string = process1(data); 

   // I would like to wait for process1 method to complete before running process2
   // I do not want to include process2 inside subscribe of process1 because I have to make few more method calls
   var process2Data: string = process2(process1Data);

   var process3Data: string = process3(process2Data);

   ...

}

How can I wait for an observable to complete before calling next method (process2, process3)? (similar like await in c#)

5 Answers

process1 in the original question is confusing as it does not return an Observable<string> (Maybe I'm using another Observable from 'rxjs/Observable').

This is the code I'm referring to (in original question):

process1(data: string) : Observable<string> {
   this.dataservice.process(data).subscribe(
            (response) => {
                return response.data;
            }
        );
}

For me, I changed it to this:

process1(data: string) : Observable<string> {
   return this.dataservice.process(data).map(  //subscribe-->map
            (response) => {
                return response.data;
            }
        );
}

Then to have something happen after process1 completes, just use subscribe like you would with any other Observable:

main(data: string) : string {
   process1(data).subscribe((process1RetVal)=>
   {
         process2(process1RetVal);
   });
}

What you need is the concatMap operator.

Every item that is emitted through the concatMap operator will be executed one by one. You can leverage this to achieve what you want.

Related