Chain and merge 3 RxJS Observables with result dependences without nesting in TypeScript and Angular 4

蓝咒 提交于 2021-02-07 14:33:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!