Search code examples
rxjsreactive-programmingobserversflatmap

How to get result after flatMap and throw a new Observer with result?


I have the following Observer method:

public __init__(httpResponse: HttpResponse<any>): Observable<any> {
    return this.initializeCredentials(httpResponse.headers, httpResponse.body['result']).flatMap((res) => {
      return this.initializePeriod(res);
    });

Where initializeCredentials() returns Observer:

private initializeCredentials(headers: HttpHeaders, body: any): Observable <any> {
   return Observable.of({'a' :1});
}

And initializePeriod() returns Observer:

private initializePeriod(profile: any): Observable<Period> {
   return return Observable.of({'b' :2});
 }

How to get result after second Observer: return this.initializePeriod(res); and throw out result farther to method __init__()?

Notice: It is important to pass result from first Observer to second this.initializePeriod().

In result I need to subsrube on __init__() and get both result from Observerbes:

this.__init__().subscribe((result) => {
      console.log(result);
});

Solution

  • If you are using rxjs5 there's a result selector function for flatMap

    public __init__(httpResponse: HttpResponse<any>): Observable<any> {
        return this.initializeCredentials(httpResponse.headers, httpResponse.body['result']).flatMap((res) => {
          return this.initializePeriod(res);
        },
    (firstRes,secondRes)=>{
    return {firstRes,secondRes}
    }
    );