3

What I'm trying to do is similar to combineLatest, but the second (inner) observable depends on the response from the first

ajax.get('/first-url')
  .map(res => new Thing(res.response)
  .someMap(thing => 
    ajax.get(`/second-url?code=${thing.code}`)
      .map(res => new OtherThing(res.response))
  ).map(([firstThing, secondThing]) => console.log(firstThing, secondThing))

Essentially, I'd like to be able to merge the two results into a single array of those results that I can use to do a third thing.

My goal is to get data A and data B because I need them BOTH to perform a certain action, and getting data B relies on already having data A.

Jason Spradlin
  • 1,407
  • 9
  • 14
  • I think `switchMap` is what you're looking for. – Danny Delott Dec 07 '18 at 16:28
  • 1
    `switchMap` switches from the first observable, to the second, while cancelling any existing instances of the second whenever the first one emits a new value (giving you a new second observable) – Jason Spradlin Dec 07 '18 at 16:30
  • @DannyDelott I see where you got your information from. There's an existing ticket on github referencing using `switchMap` and merging the results of the outer and inner observables. This was using an optional second parameter to `switchMap` called a `resultSelector`. This seems to have been deprecated as of rxjs 6.0, unfortunately. It seems like previously it worked with many of the map operators. https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#howto-result-selector-migration – Jason Spradlin Dec 07 '18 at 17:45

1 Answers1

3

I was able to get this working by doing the following:

ajax.get('/first-url')
  .map(res => new Thing(res.response)
  .mergeMap(firstThing=> 
    ajax.get(`/second-url?code=${firstThing.code}`)
      .map(res => new OtherThing(res.response))
      .map(secondThing => [firstThing, secondThing])
  ).map(([firstThing, secondThing]) => console.log(firstThing, secondThing))

Essentially, in the response from the second observable, return the exact array that I want to consume in the outer observable's .map

It appears that this is rxjs' desired way of handling this. In version 5.x of rxjs, there was a thing called a Result Selector, which could be passed in as a second parameter to create something like this (it would look a lot like the last inner .map) but this appears to have been deprecated for rxjs v6.0:

https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#howto-result-selector-migration

Jason Spradlin
  • 1,407
  • 9
  • 14