15
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?

3
  • It seems that you're looking for merge ... (even tho it does not return an array) Commented Mar 17, 2017 at 21:10
  • Why concat is not an option? - You can call toArray on concatenation result. Commented Mar 17, 2017 at 21:11
  • Concat is not an option because he wants them to run in //, concat will not run them in // Commented Mar 17, 2017 at 21:11

1 Answer 1

24

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) {})
Sign up to request clarification or add additional context in comments.

3 Comments

You're going to need to use the last operator with the source observables, as forkJoin emits an array of the obserfables' final values and concat will emit the entire stream of values.
yes, good point - you are right, behavior is a bit different. will add this to answer.
Thank you very much. I can throw away my custom Subscriber/Observable pattern I wrote! @cartant gets some brownie points.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.