Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for observable to complete

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#)

like image 967
developer Avatar asked Jul 27 '17 15:07

developer


People also ask

What is the difference between Observable and promises?

the Promise is always asynchronous, while the Observable can be either asynchronous or synchronous, the Promise can provide a single value, whereas the Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to the Observable to get a new tailored stream.

What is Take operator in RxJS?

take returns an Observable that emits only the first count values emitted by the source Observable. If the source emits fewer than count values then all of its values are emitted. After that, it completes, regardless if the source completes.

What is RxJS Observable?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

What is an Observable in angular?

Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.


2 Answers

You might try something like this...

main(data: string) : string {

    process1Data$: Observable<string> = process1(data)
        .take(1)
        .switchMap((process1Data) => return process2(process1Data);
    .
    .
    .
}

Obviously, take(1) assumes that process1(...) resolves to single value and stops. After that it switchMaps to process2 which means it starts emitting whatever observable from process2 gives. If, on the other hand, you want process2 to be ran of each result emitted from process1 then just remove take(1).

like image 151
dee zg Avatar answered Oct 05 '22 23:10

dee zg


You can use rxjs concat operator. See documentation here. concat

Basically it waits untill the first or source observable returns and then executes next.

update

You can also try operators like switch or switchmap according to your requirements.

like image 29
Steve Avatar answered Oct 06 '22 00:10

Steve