Search code examples
rxjs

Delay for every element with RXJS


I'm using RxViz to simulate different actions that comes every 1 sec. When I try

Rx.Observable.create(obs => {
  obs.next([1, 2, 3]); // or could be ['aaa', 'bbbb', 'ccc']
  obs.complete();
}).delay(1000);

on https://rxviz.com

or on my own with a console.log

it keeps displaying the three number 1, 2, 3 at the same time

There's a post about this same problem, but none of the answer works for me. I'm using Rx last version 6

How can I create an observable with a delay

[EDIT] The array can contains anything like number, string or any object


Solution

  • If you want to delay each value (by 1 sec for example), you may do something like the following:

     Rx.Observable.create(obs => {
          obs.next([1, 2, 3]);
          obs.complete();
        })
          .pipe(
            // make observable to emit each element of the array (not the whole array)
            mergeMap((x: [any]) => from(x)),
            // delay each element by 1 sec
            concatMap(x => of(x).pipe(delay(1000)))
          )
          .subscribe(x => console.log(x));
      }
    

    Here I did not modify the internals of the observable created by you. Instead, I just take your observable and apply appropriate operations to achieve what you seem to be expecting.