Applying swichMap to combine observables from both debounced and non-debounced streams

So, currently I am working with 2 observables.

  1. The obseravableClickBtn observable will send a request immediately upon click.

  2. The observableInputText observable will debounce the requests by 3 seconds.

Here is the code snippet:

obseravableClickBtn = Observable.fromEvent(document.getElementsById('btnSearch'), 'click')

observableInputText = Observable.fromEvent(this.textBoxInput1.nativeElement, 'keyup')
.merge(Observable.fromEvent(this.textBoxInput2.nativeElement, 'keyup')).debounceTime(3000)

My challenge is that during the 3-second debounce period of the observableInputText, if the btnSearch is clicked, I want to cancel the observableInputText observable and immediately send a request instead.

I attempted to solve this using:

const mergeObservable=obseravableClickBtn.merge(observableInputText).switchMap(
()=>sendRequest());

However, I am facing an issue where two requests are being made if I click btnSearch during the 3-second debounce after inputting. I require only one observable to run at a time. Is there any other operator function available for achieving this?

Answer №1

Another option to consider is using the takeUntil operator.

searchClick$: Subject = new Subject();
obseravableClickBtn.subscribe(() => {
   // Button has been clicked
   searchClick$.next(true);
});



 observableInputText = Observable.fromEvent(this.textBoxInput1.nativeElement, 'keyup')
    .merge(Observable.fromEvent(this.textBoxInput2.nativeElement, 'keyup')).pipe(debounceTime(3000), takeUntil(searchClick$));

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

When Typescript compiles to JavaScript, it may result in code that appears to be a function

In the following typescript code snippet: export enum UID { FACTORY, ROBOT } we see how it compiles to javascript: (function (UID) { UID._map = []; UID._map[0] = "FACTORY"; UID.FACTORY = 0; UID._map[1] = "ROBOT" ...

Trouble with loading images on Angular Application

After successfully building and deploying my Angular App using the build command on the cli with the deploy-url option as shown below: ng b -deploy-url /portal/ I encountered an issue where everything in the assets folder was showing up as 404 not found ...

Call a function within another function of the same class in Angular2, and utilize the properties of the first function in the

I am working on a class that contains two functions, both of which retrieve data from API calls. Let's start with the First function getQuotes(){ this.quoteService.getQuotes() .subscribe( quotes => { this.quotCode = this.quo ...

Activate the selection feature upon clicking the checkbox

I need help with enabling a select option only when a checkbox is clicked in Angular2. Form: <tr *ngFor="let user of users"> <td>{{ user.id }}</td> <td><input type="checkbox" name="switch" (click)="toggleSwitch(user.id, $ ...

Show the login form and accompanying controls in the center of the screen with Angular 6

Currently, I am working on developing a Reactive form using Angular 6. In my TypeScript file, I have successfully obtained the form instance along with form controls. The next step involves iterating through these form controls and displaying the user inpu ...

What steps can I take to prevent my authenticated user from being redirected back to the login page in Angular 16?

I have an angular 16 application and I am looking to prevent a logged-in user from accessing the login URL. I believe this can be achieved using an authGuard, but I am not sure how to implement it. In my app-routing module, the configuration looks like thi ...

Validating Firebase data for null values

Hey there, I'm currently working on a simple coding project but seems to be encountering some roadblocks. The main objective of the code is to determine if a username exists in the system or not. Here's a snippet of the data structure and codes ...

Encountering a 500 Internal Server Error while using passport-jwt in a MEAN-Stack application

Using the passport.js JWT strategy to authenticate my MEAN-Stack app has been successful for unsecured routes, but I'm encountering issues with secured routes. Despite following the documentation, all secured routes consistently return an Internal Ser ...

I have tried to install Angular Animations but have encountered difficulty importing it into my project

I attempted to incorporate Animations into my project. C:\gtaui>npm install @angular/animations --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04637065716d44342a342a34">[email protected]</a> C:&bso ...

Please indicate the generator title (for example, nx generate @nrwl/workspace:library) specifically for Angular

Currently, I am expanding my knowledge in web development. While working with Angular, I encountered an issue when trying to create a new component. The error message reads "Specify the generator name (e.g., nx generate @nrwl/workspace:library)" after exec ...

Is it possible to use a type predicate to return `void` from a function?

When creating data validation APIs, I have a common approach where I include two functions - one that returns a boolean value and another that throws an error. The throwing function typically has a void return type. interface MyType { numberField: num ...

Executing a function in the view/template with Angular 2+

Whenever a function is called in the view of an Angular component, it seems to be executed repeatedly. A typical example of this scenario can be seen below: nightclub.component.ts import { Component } from '@angular/core'; @Component({ selec ...

Leveraging Axios within VueJS - the missing piece

When working with typescript and vuejs + axios, I have included the following .catch function on a post request to handle network errors and inform the user of the status: .catch(function(error) { console.error(error.response); ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...

Is there a way to automatically validate all input fields as soon as a user arrives on the page and immediately clicks the button?

<form class="form-horizontal" (submit)="submit($event)" [formGroup]="formUser"> <input name="firstname" formControlName="firstName"> <input name="lastname" formControlName="lastName"> <button type="submit" class="btn btn-de ...

retrieving dynamic information from beyond the subscribe function

In order to implement canActivate for user routes, I need to first verify the validity of the access token. Below is the approach I am taking: export class AuthGuard implements CanActivate { data:Array<Object>; constructor(private base: BaseServ ...

Error Handling in Angular2 MVC 4 Project Route Issues

Here is the structure of my Mvc 4 Project with angular 2 implemented: Solution 'Angular2Starter' |-- angular2Starter | `-- Controllers | `-- HomeController.cs |-- src | |-- app | | |-- home | | | |-- home.component.ts | ...

Challenges faced with Angular 4 TypeScript destructuring implementation

When using the syntax {this.firstName, this.lastName} = this.data;, destructuring does not work as expected. {this.firstName, this.lastName} = this.data; The value of this.data is: {firstName: 'joe', lastName: 'smith'} However, afte ...

Error encountered with the PrimeNG Angular2 Accordion component

https://i.sstatic.net/NqDIN.png I am currently utilizing the PrimeNG accordion module. After importing all components successfully, I encountered an issue with a newly created component. Despite verifying that all modules were imported correctly, I contin ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...