Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing composite data in rxjs observable chains

I have a block of code where I'm calling observables in a chain like so:

getData().flatMap(results => {
   return callNextDataMethod(results);
}
.flatMap(results2 => {
   // next operation and so forth
})

Now, I understand that flatMap will allow me to pass the results of the previous observable to the next one. However what I need is to both do that as well as pass the results on the first. Let's assume that I do some cleanup, validation, etc on the data that comes back in getData and I want that passed to all flatMap calls down the chain. Is there an operator in rxjs that will do this for me?

Thanks

like image 636
Siegmund Nagel Avatar asked Apr 24 '17 22:04

Siegmund Nagel


People also ask

Is Forkjoin sequential?

In parallel computing, the fork–join model is a way of setting up and executing parallel programs, such that execution branches off in parallel at designated points in the program, to "join" (merge) at a subsequent point and resume sequential execution.

Are observables lazy?

No, they aren't lazy, but they are asynchronous.

What is of () RxJS?

RxJS' of() is a creational operator that allows you to create an RxJS Observable from a sequence of values. According to the official docs: of() converts the arguments to an observable sequence. In Angular, you can use the of() operator to implement many use cases.


1 Answers

You can use a map operator to combine the argument received by the flatMap projection function with the observable's result:

getData()
  .flatMap(data =>
    getMoreData(data).map(moreData => ({ data, moreData }))
  )
  .flatMap(({ data, moreData }) =>
    getEvenMoreData(moreData).map(evenMoreData => ({ data, moreData, evenMoreData }))
  )
  .flatMap(({ data, moreData, evenMoreData }) =>
    ...
like image 107
cartant Avatar answered Oct 17 '22 08:10

cartant