Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 608
Mossito Avatar asked Oct 18 '22 09:10

Mossito


1 Answers

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));
}
like image 50
atomrc Avatar answered Nov 15 '22 10:11

atomrc