Justin Thomas
Justin Thomas

Reputation: 5848

One Promise Executed at time in an Rx.Observable

I want the console.log to print 0 to 9, and only a single promise lazy evaluated at each step.

Rx.Observable.range(0,10)
   .map((i)=>new Promise((res,rej)=>setTimeout(()=>res(i),Math.random()*100)))
   .subscribe(console.log,console.error)

This code causes the promise to be logged and all the promises start at the same time...

Upvotes: 1

Views: 57

Answers (1)

Trash Can
Trash Can

Reputation: 6814

Use concatMap operator instead of map, it allows you to project the source observable one by one serially

Rx.Observable.range(0,10)
    .concatMap((i)=>new Promise((res,rej)=>setTimeout(()=>res(i),Math.random()*100)))
    .subscribe(console.log,console.error)

Upvotes: 2

Related Questions