Implementing a debounce time for a service request

I'm having an issue with the debounceTime method while trying to prevent multiple requests being sent to the server. The service is currently being called instantly without debouncing.

During a drag and drop event, I need to store positions using the saveWidgetsPosition function.

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer !== event.container) {
      transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);
    } else {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    }

    this.saveWidgetsPosition(this.columns);
  }

This is the function used to save positions:

saveWidgetsPosition(columns: any[]) {
    const columnsLabels = columns.map(x => x.map(y => y.label));

    this.userService.saveWidgetsPosition({ user: this.user, columns: columnsLabels})
        .pipe(debounceTime(5000))
        .subscribe(res => console.log(res));
}

Answer №1

Your current approach needs to be adjusted. To optimize the execution of

this.userService.saveWidgetsPosition()
, consider debouncing it instead of handling the results after debouncing.

One possible solution is:

widgetPositions = new Subject<any>();
widgetPositions.pipe(
    debounceTime(5000),
    exhaustMap((data) => this.userService.saveWidgetPositions(data))
).subscribe(result => {
    console.log(result);
});

saveWidgetsPosition(columns: any[]) {
    const columnsLabels = columns.map(x => x.map(y => y.label));

    widgetPositions.next({ user: this.user, columns: columnsLabels });
}

Answer №2

debounceTime is not designed to perform that function. It would be more appropriate to utilize delay instead.

debounceTime: Omit emitted values that occur within a specified time frame between outputs

The correct approach is to employ

<a href="https://www.learnrxjs.io/operators/utility/delay.html" rel="nofollow noreferrer">delay</a>
.
Your revised code snippet should look like this:

this.userService.saveWidgetsPosition({ user: this.user, columns: columnsLabels})
      .pipe(delay(5000))
      .subscribe(res => console.log(res));

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

What is the best way to distinguish between a button click and a li click within the same li element

In my angular and css GUI, each line is represented as an li inside a ul with a span. The functionality includes a pop-up opening when clicking on the li background and another action occurring when pressing the button (as intended). The issue arises when ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

The validation of DOM nesting has detected that a <td> element cannot be placed within an <a> element

When working on a React project with Material UI, I encountered an issue while trying to create a table. My goal was to make the entire row clickable, directing users to a page with additional information on the subject. Below is the snippet of code for th ...

Is there a way to automatically validate v-forms inside a v-data-table when the page loads?

In my data entry form, I have utilized a v-data-table with each column containing a v-form and v-text-field for direct value updates. My goal is to validate all fields upon page load to identify any incorrect data inputs. However, I am facing challenges in ...

Optimizing and scaling Firebase for improved performance

Is it possible to efficiently retrieve schedules from a database with thousands, or even millions, of records in the future? I am planning on storing schedules from healthcare professionals in a collection, but I am unsure if it is better to store them wi ...

A versatile union type in Typescript that combines dynamic properties of dynamic objects

Is there a way to create a unified union type based on the dynamic properties of an object? const config = { devices: { Brand1: ['model1'], Brand2: ['model2', 'model3'], }, }; export type DeviceBrand = keyof typeo ...

What is the best method for showcasing this console.log information in an Angular application?

I have developed a feature that displays users who are online. While it works perfectly in the console log, I am struggling to show p as the result if the user is online. Below is the code snippet: ngOnInit() { this.socket.emit('online', { r ...

There is no index signature in AxiosStatic

As I convert a hook from JavaScript to TypeScript, I encounter the following error: (alias) const axios: AxiosStatic import axios Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to ca ...

Can you identify the specific function type passed through props?

interface IProps { handleCloseModal: React.MouseEventHandler<HTMLButtonElement> returnFunction: () => void; } export default function Modal({ children, returnFunction, handleCloseModal, }: React.PropsWithChildren<IProps>) { cons ...

No overload error encountered with TypeScript function call

I am working on an async function that communicates with the backend and I need it to handle axios error messages. My goal is to display these messages in a form. export async function register( prevState: string | undefined, formData: FormData ) { t ...

Creating a TypeScript definition file that exports a class after instantiation

Currently, I am struggling with a specific typescript definition that is not functioning as expected: mapping.ts class Mapping { // } var mapping = new Mapping(); export = mapping; This setup allows for the following usage: import _mapping = require(&ap ...

The element Component is not recognized even after importing the module and applying the CUSTOM_ELEMENTS_SCHEMA schema

Recently, I integrated PinchZoom into my Angular 6 project as a node module called ngx-pinch-zoom. It's important to mention that my project is also based on Ionic 4. Within my app.module.ts file, I imported the PinchZoomModule and included CUSTOM_EL ...

Optimizing CombineLatest and LatestFrom in Redux and Angular: A Guide to Streamlining Usage

I am currently attempting to retrieve values pointing to the tokenExpiration value from the Store after the application has started. As these values are being filled asynchronously, I have added a check using a filter function to receive non-null values. ...

Step-by-step guide on implementing Form.create in TypeScript and Ant Design with function components

Having trouble compiling my form created using Form.create(). The error message I'm getting is: Argument of type 'FunctionComponent<MyProps>' is not assignable to parameter of type 'ComponentType<{}>'. Type 'Fu ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

How come Angular8's routerLinkActive is applying the active class to both the Home link and other links in the navigation bar simultaneously?

Currently, I am facing an issue with routing in my project where the home tab remains active even when I click on other tabs. I have tried adding routerLinkActiveOption as a solution, but it doesn't seem to be working for me. <ul class="nav nav-ta ...

What methods can I use to create an RXJS stream that only updates the state once all sequential calls have been successful?

Currently, I am delving into rxjs within the realm of Angular. However, I am facing difficulties in merging these concepts to accurately portray the following scenario: I initiate an HTTP request to an endpoint, which returns some data This data is then u ...

The Angular EventEmitter does not broadcast any modifications made to an array

Below is the code snippet: notes.service.ts private notes: Array<Note> = []; notesChanged = new EventEmitter<Note[]>(); getNotes() { this.getData(); console.log('getNotes()', this.notes); ...

Testing a reusable component in Angular using unit testing techniques

Currently, I am creating a test for an AppleComponent which has the following type: <T,U extends BananaComponent<T>>. This component also contains BananaComponent<T>. Target Component export class AppleComponent<T,U extends BananaCom ...

What is the method to deactivate a submit button when there have been no alterations in an input field?

I am facing an issue with multiple input fields containing user data from the database that can be edited. Even if no changes are made, the submit button remains enabled. How do I disable it? Here is the relevant function snippet from my code: const handle ...