Chain and merge 3 RxJS Observable with result dependencies without nesting in TypeScript and Angular 4

I have 3 observables that I need to relate, the result from the first is used in the other 2. They must be performed in order, and each must wait for the previous to complete. Is it possible then without nesting chain?

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 the chain, but they are still nested, is it possible to do this rather than embed them?

public doHttpProcess() {
    return this.observable1().concatMap(result1 => {
        return this.observable2(result1.json().data1)
            .concatMap(result2 => {
                return this.observable3(result1.json().data1);
            });
    });
}

Many thanks for your help.

+4
source share
1 answer

You are almost there, you just need to remove the second socket and you can link the calls concatMap

public doHttpProcess() {
    return this.observable1()
      .concatMap(result1 => this.observable2(result1.json().data1).map(result2 => ({ result1, result2 }))
      .concatMap(({ result1, result2 }) => this.observable3(result1.json().data1));
}

result2 ,

public doHttpProcess() {
    return this.observable1()
      .concatMap(result1 => this.observable2(result1.json().data1).mapTo(result1))
      .concatMap(result1 => this.observable3(result1.json().data1));
}
+2

Source: https://habr.com/ru/post/1681674/


All Articles