Observable in an Observable

Quite often you come to a point where you start with one type of Observable and you want it to turn into something else.

Example

  1. let stream$ = Rx.Observable
  2. .of(1,2,3)
  3. .flatMap((val) => {
  4. return Rx.Observable
  5. .of(val)
  6. .ajax({ url : url + }) )
  7. .map((e) => e.response )
  8. }
  9. stream.subscribe((val) => console.log(val))
  10. // { id : 1, name : 'Darth Vader' },
  11. // { id : 2, name : 'Emperor Palpatine' },
  12. // { id : 3, name : 'Luke Skywalker' }

So here we have a case of starting with values 1,2,3 and wanting those to lead up to an ajax call each

—1———2——-3———>
—json— json—json —>

The reason for us NOT doing it like this with a .map() operator

  1. let stream$ = Rx.Observable
  2. .of(1,2,3)
  3. .map((val) => {
  4. return Rx.Observable
  5. .of(val)
  6. .ajax({ url : url + }) )
  7. .map((e) => e.response )
  8. }

is that it would not give the result we want instead the result would be:

  1. // Observable, Observable, Observable

because we have created a list of observables, so three different streams. The flatMap() operator however is able to flatten these three streams into one stream called a metastream. There is however another interesting operator that we should be using when dealing with ajax generally and it’s called switchMap(). Read more about it here Cascading calls