Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs Observable run sequentially and return an array

var arr = [obs1, obs2, obs3];
Observable.forkJoin(...arr).subscribe(function (observableItems) {})

Runs observables in parallel and return an array.

How can I run the observables sequentially and return an array. I do not want to get called for each observable, so concat() is not appropriate for me.

I want to receive the same final result as forkJoin but run sequentially.

Does it exist? or do I have to code my own observable pattern?

like image 427
jsgoupil Avatar asked Mar 17 '17 19:03

jsgoupil


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.

Does forkJoin maintain order?

It's worth noting that the forkJoin operator will preserve the order of inner observables regardless of when they complete.

Does observable have next?

There is no next() on Observable; only on Subject and BehaviorSubject, which extends Subject (and both extend Observable).

Does forkJoin complete?

If no input observables are provided (e.g. an empty array is passed), then the resulting stream will complete immediately. forkJoin will wait for all passed observables to emit and complete and then it will emit an array or an object with last values from corresponding observables.


1 Answers

Just use concat and then toArray:

var arr = [obs1, obs2, obs3];
Observable.concat(...arr).toArray().subscribe(function (observableItems) {})

If you need behavior, more similar to forkJoin(to get only last results from each observables), as @cartant mentioned in comment: you will need to apply last operator on observables before concatenating them:

Observable
  .concat(...arr.map(o => o.last()))
  .toArray()
  .subscribe(function (observableItems) {})
like image 154
Bogdan Savluk Avatar answered Oct 06 '22 03:10

Bogdan Savluk