Alert: User is currently engaging in typing activity, utilizing a streamlined RXJS approach

In my current project, I am in the process of adding a feature that shows when a user is typing in a multi-user chat room. Despite my limited understanding of RXJS, I managed to come up with the code snippet below which satisfies the basic requirements for the "User is Typing" feature:

   this.messageForm.message.valueChanges
      .pipe(
        tap(() => this.convoService.isUserTyping(true)),
        debounceTime(500),
        map(() => this.convoService.isUserTyping(false))
      )
      .subscribe();

However, this implementation is not efficient as it sends too many requests to the server. My objective is to restrict requests to only 2, and utilize RXJS operators to achieve the following specific behaviors:

  1. Send a request on the initial keypress
  2. Disregard any subsequent keypresses
  3. Wait for a set duration after the last keypress
  4. Restart the timer if a new keypress occurs before the timer ends
  5. Send a request once the timer expires

Answer №1

Here is a method that ensures no side effects:

const userInput$ = this.messageForm.message.valueChanges.pipe(
  switchMap(() => concat(
    of(true),
    of(false).pipe(delay(500)),
  )),
  distinctUntilChanged(),
)

You can utilize this to handle your requests. If isUserTyping is a fire-and-forget task, you can simply use

userInput$.subscribe(typing => this.convoService.isUserTyping(typing));

If it involves an asynchronous operation (and returns an observable) I would suggest the following approach:

userInput$.pipe(
  concatMap(typing => this.convoService.isUserTyping(typing))
).subscribe();

This method ensures that all requests are executed in sequence, preventing any out-of-order issues especially in high-latency scenarios¹.


¹ If latency becomes a significant concern, additional measures such as buffering may be needed to prevent excessive backpressure on the requests. However, for the scope of this question, that level of detail is unnecessary.

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

The state array is rejecting the value from the other array, resulting in null data being returned

I am currently attempting to extract image URLs from an HTML file input in order to send them to the backend and upload them to Cloudinary. However, I am facing an issue where despite having the imagesArr populated with images, setting the images state is ...

Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example: const x = [9, 1, 0]; const y = [0, 0, 0]; c ...

Performing sequential HTTP requests on an array using Angular 4 and RxJS

Looking to perform sequential HTTP posts for each item in an array, using RxJS flatMap without success. Essentially, I'm trying to achieve the following: Each item from the 'items' array should be sent through HTTP post one by one. thi ...

Steps for setting up an Angular project as a dependency in the package.json file of another Angular project

I currently have three separate Angular cli projects labeled as X, Y, and Z. My goal is to designate [X] as the parent project and include Y and Z as npm package dependencies within X. This means that the package.json file for [X] will list the dependencie ...

What's the best way to make a toast notification appear when an API call is either successful or encounters

Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application... My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call. While a ...

"React with Typescript - a powerful combination for

I'm facing an issue trying to create a simple list of items in my code. Adding the items manually works, but when I try to map through them it doesn't work. Apologies for any language mistakes. import './App.css' const App = () => { ...

Tips for preventing duplication of the interface in Typescript React

Embarking on my first Typescript app, I am determined to maintain a structured approach by keeping styles and components in separate files. With an ambitious project scope of numerous components, I intend to utilize props for calling classes, ensuring each ...

Choosing a specific row in Angular 5

I'm completely new to Angular, so please bear with me :) I have a collection of user data that is presented in the following format: Below is my current HTML structure: EDIT - ADDED CRUD BUTTONS : <!--Add new button--> <button ty ...

Tips for testing two conditions in Angular ngIf

I am facing a little issue trying to make this *ngIf statement work as expected. My goal is to display the div only if it is empty and the user viewing it is the owner. If the user is a guest and the div is empty, then it should not be shown. Here is my cu ...

Splitting Angular Components with Angular as-split

Having trouble adding a "title" to my angular as-split-area. The titles are appearing together rather than above the as-split-area. <div style="width: 800px; height: 400px; background: yellow;"> <as-split direction="vertical&q ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Can user data be securely stored in localStorage using Angular?

I'm diving into the world of Angular and embarking on my first Angular app. I find myself pondering the safety of storing user data in localStorage. If it's not secure to do so, what alternative methods should I explore, especially since I am usi ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Strategies for Obtaining a Response Following a Function Execution in React JS

Hello, I am encountering an issue where I am calling a function and trying to get a response, but it is returning undefined. The response is being passed from the parent component to the child component. Here is the code for the component: import React fr ...

Issue with Parcel / React 18 App.js failing to refresh cache

Currently, I am developing a React application for my school project. However, I have encountered an issue where certain components are not rendering in my App.js file. Strangely, when I place these components as child components of App.js, they do render ...

Challenges arise when configuring routing in angular, nginx, and docker and encountering issues upon

Currently, I have set up angular with nginx as a reverse proxy within a docker container. The issue I am facing is related to the routing of the angular application. While I can smoothly navigate through various pages using the navbar, reloading the page ...

Is it possible to utilize AngularfireList without observables? In other words, can I retrieve an AngularfireList object directly from Firebase and then process it in

I am attempting to retrieve an object from Firebase using AngularFire and angularfirelist. However, the returned object is not what I expected. Here is my code: export class AdminProductsComponent implements OnInit { products$ : AngularFireList<unkn ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

Preventing unauthorized users from accessing routes and child components in Angular 2

Here is the project structure: AppComponent Nav Component LoginComponent Once the user successfully authenticates through the form connected to Firebase, they are directed to the section accessible only by logged-in users. AccountComponent Profile ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...