Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

Angular 2 & RxJS: map an array using Rx Observable

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?

Upvotes: 1

Views: 1756

Answers (2)

Roman Kolesnikov
Roman Kolesnikov

Reputation: 12147

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));

Upvotes: 0

martin
martin

Reputation: 96979

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

Upvotes: 2

Related Questions