Cascading calls

A cascading call means that based on what call is happening another call should take place and possibly another one based on that.

Dependant calls

A dependant call means the calls needs to happen in order. Call 2 must happen after Call 1 has returned. It might even be possible that Call2 needs be specified using data from Call 1.

Imagine you have the following scenario:

  • A user needs to login first
  • Then we can fetch their user details
  • Then we can fetch their orders

Promise approach

  1. login()
  2. .then(getUserDetails)
  3. .then(getOrdersByUser)

Rxjs approach

  1. let stream$ = Rx.Observable.of({ message : 'Logged in' })
  2. .switchMap( result => {
  3. return Rx.Observable.of({ id: 1, name : 'user' })
  4. })
  5. .switchMap((user) => {
  6. return Rx.Observable.from(
  7. [ { id: 114, userId : 1 },
  8. { id: 117, userId : 1 } ])
  9. })
  10. stream$.subscribe((orders) => {
  11. console.log('Orders', orders);
  12. })
  13. // Array of orders

I’ve simplied this one a bit in the Rxjs example but imagine instead of

  1. Rx.Observable.of()

it does the proper ajax() call like in Operators and Ajax

Semi dependant

  • We can fetch a users details
  • Then we can fetch Orders and Messages in parallell.

Promise approach

  1. getUser()
  2. .then((user) => {
  3. return Promise.all(
  4. getOrders(),
  5. getMessages()
  6. )
  7. })

Rxjs approach

  1. let stream$ = Rx.Observable.of({ id : 1, name : 'User' })
  2. stream.switchMap((user) => {
  3. return Rx.Observable.forkJoin(
  4. Rx.Observable.from([{ id : 114, user: 1}, { id : 115, user: 1}],
  5. Rx.Observable.from([{ id : 200, user: 1}, { id : 201, user: 1}])
  6. )
  7. })
  8. stream$.subscribe((result) => {
  9. console.log('Orders', result[0]);
  10. console.log('Messages', result[1]);
  11. })

GOTCHAS

We are doing switchMap() instead of flatMap() so we can abandon an ajax call if necessary, this will make more sense in Auto complete recipe