RxJS BehaviorSubject allows you to retrieve the current value or obtain a new one depending on a specific condition

I am managing a subject that consumers subscribe to:

private request$: Subject<Service> = new BehaviorSubject(null);

Upon initialization, my components utilize this function:

public service(id: number): Observable<Service> {
    return this.request$
        .pipe(
            switchMap((request) => request && request.serviceId ? of(request) : this.requestById(id)));
}

and make a service call:

private requestById(serviceId: number): Observable<Service> {
    // http call 
}

Various components invoke this function with different ids. I want to update the subject if the incoming id parameter value does not match the current subject's id value.

Is it possible to achieve this? I came across an iif function, but I'm unsure if it's the right fit for me.

Thank you

Answer №1

Here are the steps you can take:

public fetchService(id: number): Observable<Service> {
    return this.requests$
        .pipe(
          // Ensures only one evaluation after fetching service
          take(1),
          switchMap((request) => {
            if(request && request.serviceId === id) {
              return of(request);
            } else {
              return this.retrieveRequestById(id) 
                         .pipe(
                           // Assuming the response from retrieveRequestById is an instance of 'Service'; 
                           // Update the subject
                           tap(s => this.subjectRequests$.next(s))
                         );
            }
          })
        );
  }

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

Having trouble retrieving data from JSON using JavaScript

Hey folks, I need some help with the following code snippet: function retrieveClientIP() { $.getJSON("http://192.168.127.2/getipclient.php?callback=?", function(json) { eval(json.ip); });} This function is used to fetch the IP address of visitors. When i ...

How can I use jQuery to target and modify multiple elements simultaneously

I've been struggling for the past couple of hours trying to use prop to change the values of two items in a button. One item updates successfully, but the other one doesn't and I can't figure out why. Here is the HTML: <input type=&apos ...

Warning: Unhandled Promise Rejection - Alert: Unhandled Promise Rejection Detected - Attention: Deprecation Notice

Encountering the following error message: (node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24 at Layer.han ...

Revamp your JavaScript code to trigger when the clock strikes bold!

Having trouble setting up JavaScript to automatically bold the next clock time. Any tips on rewriting the JavaScript? For instance, if it is currently 6:49, I want the next clock time of 7:32 to be automatically bolded. And when the time reaches 7:32, I wa ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

Exploring the chosen choice in the Material Design Lite select box

Consider the following scenario. If I want to extract the name of the country chosen using JavaScript, how can this be achieved? <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select getmdl-select__fullwidth"> ...

What is the best way to implement a delay before calling the owlCarousel function?

Is there a way to delay calling the owlCarousel function for 5 seconds? I attempted the following: $(document).ready(function(){ setInterval(function(){ $(".demo-slide").owlCarousel(); },5000); }); However, I encountered ...

Error Encountered with Google Authentication in Localhost:3001 - Warning of 'Blocked Access'

Encountering a Next-auth Google authentication issue on my localhost development setup. Admin side (localhost:3000) and client side (localhost:3001) of e-commerce website are separate instances. Error message "access blocked" when trying Google authentica ...

Unable to apply programatically loaded attributes to the rangeslider.js plugin

I'm having trouble with my graph editor that uses the rangeslider.js plugin. The bars are not updating properly most of the time, and sometimes they don't work at all. I have a demo available here and a simplified version on Fiddle. Strangely, so ...

Break up a list into separate paragraphs and style each word using individual CSS

I have a user-generated paragraph that consists of a list of words separated by commas, such as "dog, cat, hamster, turtle." I want to be able to individually assign attributes to each word in the list. Check out this image for reference In the example i ...

Bootstrap does not show submenus on its navigation menus

I am currently designing a menu with Bootstrap, but for some reason, the submenu items are not showing up. https://i.stack.imgur.com/qZqyf.png After carefully reviewing the HTML code multiple times, I am unable to identify any issues. I am now questionin ...

"Encountering a Javascript issue while trying to apply a CSS class to a

Encountering issues in Safari desktop / mobile and Internet Explorer. The error message states: In Safari: TypeError: Attempted to assign to readonly property. IE Edge: Assignment to read-only properties is not allowed in strict mode The problem arises ...

How can data be transferred from a parent component to a child component using MaterialUI's styling functionality?

Recently delving into the world of reactjs, I've been tinkering with a basic page that incorporates authentication using state. To spruce up the design, I decided to use the MaterialUI framework. The issue I'm facing is related to sending the lo ...

Is there a pub/sub framework specifically designed for managing events in Angular?

Having a background in WPF with Prism, I am familiar with the IEventAggregator interface. It allows you to define events that can be subscribed to from controllers and then triggered by another controller. This method enables communication between controll ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

What is the proper method for utilizing a conditional header in an rtk query?

How can I implement conditional header authentication using rtk query? I need to pass headers for all requests except refresh token, where headers should be empty. Is it possible to achieve this by setting a condition or using two separate fetchBaseQuery ...

Melodic Streaming Platform

I currently have a client-side application built using React. I have a collection of music stored on my Google Drive that I would like to stream online continuously. I lack experience in server-side programming. Can you suggest any resources or steps I s ...

Retrieve the number of days, hours, and minutes from a given

Is it possible to use JavaScript (jQuery) to calculate the number of days, hours, and minutes left before a specific future date? For example, if I have a timestamp of 1457136000000, how can I determine the amount of time remaining in terms of days, hours ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Updating Kendo by modifying the Angular model

While working on a project with Angular, I recently discovered the Kendo-Angular project available at . I successfully integrated Angular-Kendo into my project and it seems to be functioning well, except for updating models in the way I am accustomed to. ...