Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  166] [ 4]  / answers: 1 / hits: 58658  / 7 Years ago, thu, july 27, 2017, 12:00:00

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


More From » angular

 Answers
15

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


[#56952] Tuesday, July 25, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;