RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website.

Here's how it works at the moment:

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

I'm wondering if there's a more concise way to achieve the same outcome with less code. The nesting of switchMap() and concatMap() is a bit cumbersome for me.

Any suggestions or advice would be greatly appreciated.

Edit: The example provided here is a simplified version of what I'm currently working on in my project. I'm looking for a simpler method to transition from an Observable<string[]> to an Observable while adding a one-second delay between emissions.

Answer №1

To ensure each emission is delivered sequentially with a specified time interval, you can utilize the concatMap() and delay() operators.

const stringArray = [
  'Preparing for launch',
  'Initiating countdown',
  'Blast off!'
];

(from(stringArray)
  .pipe(
    concatMap(message => 
      of(message).pipe(delay(2_000))
    ),
  )
  .subscribe()
);

Answer №2

When you want to combine the items 'one', 'two', and 'three' with a time interval of 1000 milliseconds between each item, you can use the zipWith operator along with the interval function. The result will be logged to the console.

If you prefer to start immediately instead, you can replace the interval function with timer(0, 1000).

Answer №3

If I were to implement this, my approach would involve the use of the provided code snippet:

const stringsArray$ = of([
  'Preparing for action',
  'Setting things in motion',
  'Greetings'
]);

stringsArray$.pipe(
  mergeMap((str) => str),
  zip(timer(1000, 1000)),
  map(([str]) => str),
  tap(msg => {
    console.log(`Displaying message: ${msg}`);
  })
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comparing a number to the sum of numbers in JavaScript using VUE

Newbie in the world of JavaScript and VUE. In my data, I have a variable called numberOfItems with a value of 10. I am trying to check if this value is equal to the total sum of 5 different variables. var numberOfItems = 10 var destinations = (this.campa ...

`MongoDb aggregation performance degradation with numerous collections (join)`

I am currently working on a project using the MEAN stack and I have noticed that I am utilizing a significant number of collections in my aggregation, resulting in a heavy reliance on lookup. This has had a negative impact on performance, causing the execu ...

The Heroku system encountered an issue: ENOENT - file or directory not found, trying to access '.env'

I'm encountering issues while attempting to deploy my application to Heroku: Error: ENOENT: no such file or directory, open '.env' 2019-04-10T01:38:23.050188+00:00 app[web.1]: 1 at Object.openSync (fs.js:438:3) 2019-04-10T01:38:23 ...

Child_process module spawn method in Node.js

When I attempt to play an audio stream using the mpg123 command, everything works perfectly fine. I have also implemented a method to terminate the process successfully. However, I am struggling to retrieve output from the executed command. Despite follow ...

Cannot access Injectable service in Angular2

In the angular2 application, there is a service named HttpClient. The purpose of this service is to include an authorization header in every request sent by the application to endpoints. import { Injectable } from '@angular/core'; import { He ...

The UPDATE query failed to make any changes to the data stored in the MySQL

Currently I am developing an application using express.js. In my project, I have incorporated the "mysql" add-on (https://www.npmjs.com/package/mysql). The issue I am facing is while sending an UPDATE query to the server and receiving a response that shows ...

Enhance row visibility by clicking a button in an ajax table

I'm facing an issue where I am trying to apply a highlight class to the selected row in an ajax table when clicking on the edit button, but for some reason my code is not working as expected. Can someone assist me with this problem? Thank you in advan ...

How can you utilize Angular Signals in combination with HostBinding to dynamically update styles?

Within a component called app-test, the following code is present: @Input({ transform: booleanAttribute }) reverse: boolean = false; @HostBinding('style.flex-direction') direction: string = this.reverse ? 'column-reverse' : &ap ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

Is it possible for a nodejs server to handle both grpc and express servers simultaneously, or do they need to be separate servers?

I'm currently in the process of building a REST server using Node/Express. I'm curious about how to incorporate a GRPC server within the same setup. Would it be possible to run both servers on the same NodeJS instance, or is it recommended to hav ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

How to pass a data property as a function argument in Vue.js

Instead of using a few methods that are structured like this: showDiv1(){ this.showDiv1 = true }, showDiv2(){ this.showDiv2 = true } I am attempting to consolidate them into one method like so: showElements(...elementNames){ elementNames. ...

Error encountered in Node.js: The listener must be a function

I've been working on adapting the solution provided in (How to create a simple http proxy in node.js?) from HTTP to HTTPS. However, upon attempting to access the proxy through my browser, the server abruptly stops and throws the following error: eve ...

Incorporate functionality into a button using jQuery

I am working on a table that displays data in different levels (Parent, Child, Grandson). When I click on the parent row, it expands to show new rows related to the child level. Similarly, clicking on a child row reveals a third level known as the grandson ...

Combining information from two different sources to create a more comprehensive dataset

Two get requests are returning the following data: [{ id: 1, hId: 2 }, { id: 6, hId: 1 }] The second request returns: [{ id: 1, name: 'Bob' }, { id: 2, name: 'Billy' }, { id: 6, name: 'John' }] The object ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Dynamic Images with Next.js

Currently, I am utilizing next.js and attempting to dynamically retrieve images in the following manner: {list.map((prod) => ( <div className={styles.singleProduct}> <h6>{prod.Brand.toUpperCase()}</h6> <p&g ...

Achieving Jest integration with Angular 9 in a Storybook setup

We are currently utilizing Storybook 5 alongside Angular 9, with Jest 26 for some of the testing procedures. The issue we're facing arises when using Typescript version below 3.8.0 - a requirement for Angular 9's ng build --prod. This results in ...

karma: Error: Unable to access the 'prototype' property of an undefined object

Whenever I attempt to inject my service, the following error occurs: (function () { describe('Test', function () { var $scope, $state, service,ctrl; beforeEach(function() { module('moduleApp'); ...

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...