Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS emit array of strings, one second apart from each other

I have a block of code that is responsible for taking an Observable<string[]>, then mapping that to Observable<string> and emitting the values 1 second apart from each other.

Think of this like a message ticker on a website.

My current code is working below:

    const arrayOfStrings$ = of([
        'Warming things up',
        'Getting things ready',
        'Welcome'
    ]);

    this.messages$ = arrayOfStrings$.pipe(
        switchMap((messages) => from(messages).pipe(
            concatMap((innerMessage) => of(innerMessage).pipe(delay(1000))),
        )),
        tap((message) => {
            console.log(`Message: ${message}`);
        })
    );

Is there a better way to do this with less code? It's mainly the switchMap() and concatMap() inside each other that is bothering me.

Thanks for any help and suggestions.

Edit: This is a simplified version of what I have running in my actual project. I am just trying to find an easier way to go from an Observable<string[]> to an Observable and delay each emission one second apart after each emission

like image 208
Damian C Avatar asked Oct 31 '25 21:10

Damian C


1 Answers

You can use the concatMap() and delay() operators to make sure that each emission will be delivered one-by-one with a specified time interval.

const arrayOfStrings = [
  'Warming things up',
  'Getting things ready',
  'Welcome'
];

(from(arrayOfStrings)
  .pipe(
    concatMap(message => 
      of(message).pipe(delay(1_000))
    ),
  )
  .subscribe()
);
like image 68
martin Avatar answered Nov 03 '25 12:11

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!