rxjs

RxJS switchmap-like operator that gives me the result of the first observable too


Suppose I want to do the following

this.http.get(...).pipe(
  switchMap(httpResult => this.database.storeValue(httpResult.objectA)
).subscribe((databaseResult) => {
  // I have lost the reference to `httpResult`
};

in my subscribe, I no longer have httpResult. So ideally after doing the first switchMap I should put another operator that gives me the result of both http.get and database.storevalue. But none of the operators using the RxJS decision tree seem to give me what I need. I have been looking into concatWith and concatMap (since these run sequentially) but I don't seem to get there though...

Ideally, the result should look something along these lines i.m.o.

this.http.get(...).pipe(
    switchMap(httpResult => this.database.storeValue(httpResult.objectA)),
    otherOperator()
  )
  .subscribe(([httpResult, databaseResult]) => {
  // Do things with both results.
};

Solution

  • Chain a map to the switchMap return value, which returns both the values.

    this.http.get(...).pipe(
      switchMap(httpResult => 
        this.database.storeValue(httpResult.objectA).pipe(
          map((databaseResult: any) => ([httpResult, databaseResult]),
        )
      )
    ).subscribe(([httpResult, databaseResult]) => {
      // I have lost the reference to `httpResult`
    };