Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?



import {
  HttpHandler,
  HttpInterceptor,
  HttpParams,
  HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@core/services/auth.service';
import { exhaustMap, take } from 'rxjs/operators';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
  constructor(private authService: AuthenticationService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return this.authService.checkUser.pipe(
      take(1),
      exhaustMap((user) => {
        if (!user) {
          return next.handle(req);
        }
        const modifiedReq = req.clone({
          params: new HttpParams().set('auth', user!.token!),
        });

        return next.handle(modifiedReq);
      })
    );
  }
}


This specific file serves as an interceptor that adjusts the request URL by including 'auth' query parameters with a token value obtained from the user object. However, it may be challenging to comprehend the inner workings of the exhaustMap function.

Answer №1

exhaustMap is a type of higher order pipe operator that subscribes to the observable being piped and, for each emitted value, returns a new observable based on the function provided.

The key difference between exhaustMap, switchMap, concatMap, and mergeMap lies in how they handle scenarios where the mapped observable has not completed but a new value is emitted by the source observable.

In this specific case, exhaustMap is utilized. This means that if a new value is emitted from the source observable while the previously mapped observable is still active, the new value will be ignored until the ongoing operation completes.

Only after the previous operation finishes will new values from the source observable be processed by the inner observable once again.

Answer №2

Imagine a situation where this piece of code this.authService.emitUser is considered as the main source of data, also known as a source observable. If this source emits a user named Theri, and this data is being handled by an operation called exhaustMap, then no matter how many times the source observable emits additional users like Muthu, the exhaustMap will continue processing the initial user Theri until its task is completed. Only after finishing with Theri, will the operations move on to handle the new user Muthu.

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

Create a router link in Vue using the command "Vue

I have a Vue application that displays videos. I am looking to automatically generate a random router link every time I click on: <router-link to="/video/this_value_to_be_random">Random video</router-link> Within the component: <vue-vide ...

Collect the GET parameters as an array of strings when there is only one value

How can I properly pass a string array as a parameter for a GET call? // Passing one value param: filters=Something value: filters: 'Something' // Passing multiple values param: filters=Something&filters=Something else value: filters: [ &ap ...

Using jQuery to animate a form submission in CodeIgniter

I have integrated two jQuery plugins into my application, which are: jQuery validate : . jQuery blockui : http://malsup.com/jquery/block/#download The application is developed using PHP Codeigniter and jQuery. It consists of a form created with the fol ...

varied reactions between componentDidMount and useEffect when employing jquery emoji plugin

Currently, I am facing an issue with a jquery emoji plugin that I need to use on one of my components until I complete building a custom plugin. Interestingly, when I call the emoji plugin inside componentDidMount, everything works fine, except for the ab ...

Creating consistency in tab spacing within a text area

At the moment, I am utilizing an HTML textarea attribute to collect input from users and then displaying that text back to them formatted. However, there seems to be an issue with how it handles tabs. For instance, when attempting to input the following: ...

Problem: Unable to locate the TypeScript declaration file

I am facing an issue with my TypeScript configuration. I have two files in /src/models/: User.ts and User.d.ts. In User.ts, I am building a class and trying to use an interface declaration for an object defined in User.d.ts. However, User.ts is unable to a ...

Real-time Data Stream and Navigation Bar Location

Utilizing the EventSource API, I am pulling data from a MySQL database and showcasing it on a website. Everything is running smoothly as planned, but my goal is to exhibit the data in a fixed height div, with the scrollbar constantly positioned at the bott ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

How to Troubleshoot VueJS Component Render Issues After Importing/Calling Components

In one of my projects, I successfully implemented a file uploader component using import and component statements. import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader); This implementation ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

Follow button on LinkedIn is secure with Google Chrome's Content Security Policy set to script-src report-sample

Having an issue trying to add a LinkedIn Follow button to the website. It works perfectly in Firefox, but is not functioning in Chrome. The Console displays the following error: The source list for Content Security Policy directive 'script-src&apos ...

Exploring the images in a continuous loop

Looking to create a unique image looping effect using HTML, CSS, and Jquery/Javascript. The concept is to display several images on one page that do not move, but loop through them one at a time while displaying text above the current image. For example, ...

Updating Variables in Azure DevOps Code Prior to DeploymentORModifying Variables

Can Azure DevOps automate code updates upon release? For instance, in my React app, I have a setting file with export const ISPROD = false. I want Azure DevOps to modify this value to true before building and deploying the app. Is this achievable? Please ...

Challenges in developing complex single-page applications

Currently, I am in the process of developing an extensive single-page web/javascript application that is going to be quite large. The technologies I am utilizing include ASP.NET MVC4, jquery, knockout.js, and amplify.js. One obstacle I am encountering is ...

Custom mute bot using Discord.js with the ability to specify duration and provide a reason

I'm creating a discord.js mute bot and encountering some issues with its functionality. Is there a way to program it so that when someone types the command !mute User, it automatically sets the time to 30min and the reason as No reason Specified. How ...

Activate every switch using only one switch

Below is the table I am working with. I'm trying to toggle all switches with the class name the-checkbox-input when the first switch with the class name checkbox-input-main is toggled. The code snippet I have tried doesn't seem to be working, ev ...

What is the best way to transfer data between my express middleware functions?

Hello, I am new to working with Javascript/Node/Express and currently trying to interact with the Facebook Graph API. Below is an Express middleware function that I have set up: My goal is to follow these steps: Acquire a user authentication token fro ...

Fetching information with request query parameters in Node.js

Working on implementing email verification using nodemailer for user sign-ups. The process involves sending out an email containing a link (usually something like localhost:3000/verify/?id=##). After the user clicks the link, I can see that a GET request ...

Passing data from a container component to a Redux Form component in React with TypeScript

One of my Form container components looks like this: class PersonalDetailContainer extends React.Component<PropTypes> { onSubmit = async (fields: PersonalFields) => { this.props.savePersonalDetail(fields); }; render(): JSX.Element { ...