Bazinga777
Bazinga777

Reputation: 5281

Delaying and iterating an object with rxjs

I am trying to loop through the keys in an object and iterate over them after a set interval between one key to another. I am trying to achieve this using the interval operator but I have been unsuccessful in doing so.

let obj = { 'a': [1,23,3], 'b': [12,23,2] };
 for(let key in data) {
      Observable.interval(5000).subscribe( () => {
         // perform operation with data[key]      
       });
  }

I don't see any delay between my loops and all i am getting is a sudden iteration which is not different from the normal loop beahvior.

Upvotes: 0

Views: 2326

Answers (2)

martin
martin

Reputation: 96949

That's because you're creating a new Observable in each iteration.

I guess you wanted to make something like this:

Observable.from(Object.keys(obj))
    .concatMap(item => Observable.of(item).delay(5000))
    .subscribe(item => console.log(item));

The actual delay is performed by concatMap that waits until each inner Observable completes before subscribing to the next one.

Upvotes: 2

Julia Passynkova
Julia Passynkova

Reputation: 17889

You can use zip and timer operators. Timer is like interval with with arg 0 - will start emitting immediately.

let obj = { 'a': [1,23,3], 'b': [12,23,2] };

Rx.Observable.zip(
   Rx.Observable.timer(0, 5000),
   Rx.Observable.from(Object.entries(obj)),
   (timer,val)=>val
)
.subscribe(x=>console.log(x))

Upvotes: 0

Related Questions