1

I have an array of numbers like this: [1, 2, 3], and HTTP service that has function to load data object by number like this:

function get(id: number): Observable<object>

How to map my original array of numbers to array of objects preserving order of elements?

2 Answers 2

2

You can use concatMap operator.

const Observable = Rx.Observable;

function mockHttpRequest(i) {
  return Observable.of(i).delay(500);
}

Observable.from([1, 2, 3])
    .concatMap(i => mockHttpRequest(i))
    .subscribe(data => console.log(data));

This simulates multiple HTTP requests where each one is delayed by 500ms. Operator concatMap() guarantees that the Observables will becalled in order.

See live demo: https://jsbin.com/subuxo/edit?js,console

Sign up to request clarification or add additional context in comments.

2 Comments

1) I want Observables to be called simultaneously, not in order, I want the results to be in order. 2)I want to get the resulted array back, not individual values
@Rem They you need to formulate your question better. You didn't mention anywhere you want to run request in parallel. Btw, have a look at forkJoin operator.
0

Thanks to @martin I found this solution:

const myPromise = val => new Promise(resolve => setTimeout(() => resolve(`Promise Resolved: ${val}`), 
                                                          Math.round(Math.random() * 1000 + 1000)))
const queue = Rx.Observable.of([1,2,3,4,5]);
const result = queue
  .mergeMap(q => Rx.Observable.forkJoin(...q.map(myPromise)));
const subscribeTwo = result.subscribe(val => console.log(val));

Comments

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.