问题
I have 3 observables that i need to chain, result from first one is used in the other 2. They must run in order and each one must wait for the previous one to finish. Is it possible to chain then without nesting?
public observable1(): Observable<Response> {
let headers = new Headers();
headers.append("Content-Range", "bytes */*");
let requestOptions = new RequestOptions({headers: headers});
return this.http.put(url, "", requestOptions);
}
public observable2(data1url): Observable<Response> {
let headers = new Headers();
headers.append("Content-Range", "bytes */*");
let requestOptions = new RequestOptions({headers: headers});
return this.http.put(data1url, "", requestOptions);
}
public observable3(data1url): Observable<Response> {
let headers = new Headers();
headers.append("Content-Range", "bytes */*");
let requestOptions = new RequestOptions({headers: headers});
return this.http.put(data1url, "", requestOptions);
}
This is the only way i found to chain them but they are still nested, is it posible to do this and not to nest them?
public doHttpProcess() {
return this.observable1().concatMap(result1 => {
return this.observable2(result1.json().data1)
.concatMap(result2 => {
return this.observable3(result1.json().data1);
});
});
}
Thank you very much for your help
回答1:
You are almost there, you just need to remove the second nesting and you can chain the concatMap
calls
public doHttpProcess() {
return this.observable1()
.concatMap(result1 => this.observable2(result1.json().data1).map(result2 => ({ result1, result2 }))
.concatMap(({ result1, result2 }) => this.observable3(result1.json().data1));
}
And if you don't need result2
to generate the last observable, you can simplify to
public doHttpProcess() {
return this.observable1()
.concatMap(result1 => this.observable2(result1.json().data1).mapTo(result1))
.concatMap(result1 => this.observable3(result1.json().data1));
}
来源:https://stackoverflow.com/questions/45161800/chain-and-merge-3-rxjs-observables-with-result-dependences-without-nesting-in-ty