Picci
Picci

Reputation: 17752

Combining 2 Observables so that one emits the next value only when the second emits

I have an Observable Obs1 which has been created with the method from starting from an Array of objects.

Let's assume the Array has 10 objects, this means that Obs1 emits 10 times and then terminates.

For each of the objects emitted by Obs1 I want to execute a function which returns an Observable. The Observables returned by the function are therefore of the same number as the elements of the Array, let's call them Obs2-1 Obs2-2 ... Obs2-10. Such Observables emit just 1 value and then complete.

I would like to link somehow Obs1 to series of Observables Obs2-1 ... Obs2-10 so that Obs1 emits its (n+1)-th value when Obs2-n emits.

A real example can make this thing more clear. Let's assume I have an array of strings. Each string is the name of a file. I have a function r-w-files(files: Array<string>) which reads each file in the list and writes it in another directory.

I want to execute this read write logic for a big number of files and therefore, to avoid having too many files open at the same time, I want to divide the big initial list in smaller chunks and then SEQUENTIALLY process them with the function r-w-files(files: Array<string>).

What I am imagining is to have a certain form of buffer of chunks which

Is there any way to implement such logic with Observable operators?

Upvotes: 0

Views: 522

Answers (1)

ZahiC
ZahiC

Reputation: 14687

To switch Observables sequentially, you can use concatMap:

Rx.Observable.from(['value 1', 'value 2', 'value 3'])
  .concatMap(value => createNewObservable(value))
  .subscribe()

concatMap waits until the previously created Observable completes before switching to the next one.

Upvotes: 2

Related Questions