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

finding the source file or code where a particular html element is being generated

In the HTML file I have, there are multiple JavaScript files added. Whenever I run the HTML file, a title tag is automatically created in my HTML file. I do not want this title tag to appear in my HTML file. How can I prevent this from happening? Or how c ...

Guide to retrieving environment variables within React/Node.js applications running in Kubernetes pods

While setting environment variables in Kubernetes pods, I encountered an issue when trying to access them in either Node.js or React front-end code using process.env.TEST (where TEST is present in the environment as secrets), as it always returned undefine ...

Integrate AngularJS service with Angular framework

Attempting to utilize the $log service within an angular 2 app, it seems that the following steps are necessary: Set up a module that includes the service you wish to inject. Utilize UpgradeAdapter's upgradeNg1Provider method. Therefore, I proceede ...

The GET request on the Express route is malfunctioning, causing the Postman request to time out after getting stuck for some

My Express app seems to be experiencing some issues with the GET route. When making a request using Postman, the response gets stuck for a while before fetching. The GET route is properly set up with all necessary request parsers and the app initialized an ...

Is it possible to run Next.js 13 with React.js version 17?

Can Next.js 13 be used with React version 17? I upgraded my Next.js to version 13 and encountered a minimum requirement of React version 18, which is not compatible with my codebase. Is it possible to use Next.js 13 with React version 17 instead? ...

The Expressjs router prioritizes resolving before retrieving data from Firestore

UPDATE: Upon further investigation, I discovered that by adding "async" to the function signature, the output now displays in the intended order. However, I am still encountering an error regarding setting headers after they have already been sent, even th ...

Discover the steps to convert an image to base64 while circumventing the restrictions of the same-origin policy

I've been struggling to convert an image link to base64 in order to store it on the client-side browser (IndexedDB). Despite searching for a solution for days, I have not been able to find one that addresses my issue. While I can successfully convert ...

What are the steps for retrieving a JSON object within an array?

var jsonData = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue" :{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text" :"Size32","price":"22","isSelec ...

Is there a way to verify if the current event marks the conclusion of the events transmitted to a webhook?

Currently, I am in the process of coding a Google Apps Script web app that will react to events from the Telegram API using a chat bot. The first step was setting up a webhook to collect these events through the Google webhook. Since logger.log is unavaila ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Send a parameter to a React hook

I am facing an issue with a Component that is using a separate hook. I am unable to pass any value to that hook, which is necessary for my use case. const onEdit = (index: number) => useMediaLinkImage(img => { setNodeImages(imgData => { ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

The state in the React components' array functions is not current

import React, { useState } from "react"; const Person = ({ id, name, age, deleteThisPerson }) => { return ( <div className="person"> <p>{name}</p> <p>{age}</p> <button onClick ...

Organizer featuring Outlook-inspired capabilities

My goal is to develop a system for efficiently managing appointments. Upon opening the application, I want to display a calendar control that will retrieve an individual's schedule from a SQL server database. For example, if the user has meetings sch ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

Use Javascript to extract an array of strings enclosed in double quotes

Is there a way to extract an array containing ["13139","13141", "13140"] from the following data structure? { "13139": [tx[0]], "13141": [tx[1]], "13140": [tx[2]] } I attempted to use JS ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...

Strange Node.js: I always avoid utilizing `require()`, yet encountered an unexpected error

For more information on this particular issue, please refer to this link It's quite puzzling as I haven't used the require() function in my code, yet I'm receiving an error telling me not to use it. How odd! The problematic code snippet i ...

What's the best way to conceal the navbar while attempting to print the page?

Currently, I am working on developing an application for my school project. One of the features is an invoice sheet with a print option. However, when I try to print by clicking the button or using ctrl+p, the navbar appears in a chaotic and disorganized m ...