Ways to differentiate between the sources of two cold Observables (not just the possible data streams they may produce)

Situation: Within my Angular application, I am using publishReplay to store and replay specific Http requests. However, I encountered an issue where I need the cached observable source to update itself and create a new cached observable with publishReplay whenever a URL parameter change is detected.

I have been unable to compare the newly proposed observable with the existing cached observable's source effectively in order to achieve this desired functionality.

Seeking Solution: I am looking for a way to compare two observables (specifically their URLs) without subscribing to them. This comparison will help me determine if the parameters on the URL have changed so that I can decide whether to refresh the cache or return the cached result.

Here is an example of what I have tried unsuccessfully so far:


protected isEntreeValid<T>(key: ICacheKeyConstantsModel, source: Observable<T>): boolean {
    if (!this.has(key)) { return false; }
    if (this.has(key)) {
        let origSource = this.cache.registry.get(key).source;
        console.log('source: ', source);
        console.log('are they equal', source.source === origSource.source);
        if (source.source !== origSource.source) { return false; }
    }

    return true;
}

Explanation: The 'source' parameter in the above method points to an http.get function stored in a Map. It is crucial to evaluate this source when a key already exists in order to check for any URL parameter changes and handle the cache accordingly.

Note: My main focus is on comparing the source properties of the Observables and not connecting to them or analyzing the streams they emit.

Update: I discovered the location of the property needed for comparison down the structure of the Observables. Is there a better way to access this information instead of drilling down so deeply?

Property Location: Observable.value.source.source.source.source.source

Structure at Location:

{


value: HttpRequest

body: null

headers: HttpHeaders 

method: "GET"

params: HttpParams 

reportProgress: false

responseType: "json"

url: "https://my-dev-server.com/primary/HealthCareApp/Patients"

urlWithParams: "https://my-dev-server.com/primary/HealthCareApp/Patients"

Question: Are there efficient ways to flatten or drill-down to the innermost Observable without subscribing?

Update 2:

Currently, I am using a method like the one below to extract the innerObservable, but I am open to exploring better alternatives:


private extractInnerObservable<T>(source: Observable<T>): Observable<T> {
    let target = observableOf(source)['value'];
    while (target['source']) {
        target = target['source'];
    }

    return target;
}

Final Notes:

While I continue to explore other options, I wanted to provide updates on my progress with addressing the initial problem. Although the current solution may not be the most elegant, it has helped me make some headway. Hopefully, sharing this process will assist others facing similar challenges.

Answer №1

Perhaps consider flipping your approach on this issue. If there's a parameter that needs to be updated in the cached request, you can use operators to make the necessary changes...

private paramSource = new Subject<string>(); // define appropriate type
cached$ = this.paramSource.pipe(
  distinctUntilChanged(), // custom comparison function could be added here
  switchMap(param => this.makeRequest(param)),
  shareReplay(1) // choose caching strategy
);

// Call this method whenever you need to trigger the observable inspection
updateParam(param: string) {
  this.paramSource.next(param);
}

I'm not entirely sure if this directly meets your objectives, as I may lack full clarity on your requirements. Nonetheless, hopefully, this is helpful.

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

Angular2 Cache: Enhance Your Application's Performance

Currently seeking a cache solution for my Angular2 application. Imagine we have a massive collection of Movie objects stored on a server, too many to fetch all at once. The server offers a REST endpoint: getMovie(String id) On the client side, I need a s ...

When using TypeScript, default imports can only be done with the 'esModuleInterop' flag enabled

Below is my current code snippet in index.ts: import { User } from "./datatypes" import express from 'express'; console.log("hello world") Displayed is the content of my package.json: { "name": "simple_app& ...

Retrieve the value of a variable to access an object property dynamically in React Native using TypeScript

As I attempted to create dynamic styles for this component, my goal was to determine the styles based on a string passed in as a property. Here is the code snippet: export type MyComponentProps = { styleName: string; } const MyComponent = (props: MyComp ...

The HttpClient.get('/') request with {observe: 'response'} is failing to retrieve some headers

Currently, I'm in the process of writing an API GET request by utilizing HttpClient.get(). Upon passing in the option to observe the response, I've encountered an issue where accessing the .keys() does not provide me with any headers apart from C ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

MUI provides the flexibility to adjust the opacity separately for Chip labels/icons and backgrounds

My objective is to customize the opacity of label/icon and background in MUI Chip. I want the label & icon to have an opacity of 1, while the background should have an opacity of 0.0571. Technologies used in this project include React, TypeScript, Materia ...

Backend communication functions seamlessly within the service scope, yet encounters obstacles beyond the service boundaries

I'm facing an issue with accessing data from my backend. Although the service successfully retrieves and logs the data, when I try to use that service in a different module, it either shows "undefined" or "Observable". Does anyone have any suggestions ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

What is the process for incorporating buttons into an Angular mat-table?

I have successfully utilized Angular mat-table to showcase data retrieved from a database: view the image description here <table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5"> <ng-co ...

What is the best way to dynamically load a third-party module in Angular 2?

One way to dynamically load third-party modules in Angular 2, especially for production builds using Angular CLI with Ahead-of-Time (AOT) compilation, is by leveraging webpack's functionality. Webpack generates build files for both eagerly and lazily ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Before proceeding to update in Angular 8, ensure the repository is not dirty. Commit or stash any changes that have been

Encountered an Issue The repository is not clean. Please commit or stash any changes before updating. When upgrading from version 7 to Angular 8, I faced this error. To find out more about the upgrade process, you can visit the Angular Guide for Upgra ...

Utilize the useTheme type from Emotion Js within ReactJs using Typescript

Greetings! As a newcomer to typescript, I find myself with a query regarding the use of Theme in emotionJs. Here's the snippet of code that has been causing me some trouble: const GlobalStyle: React.FC = (props) => { const Theme = useTheme(); ...

Issue with Sending Messages using SignalR in .NET and Angular

I am attempting to make a simple SignalR example work, following Microsoft's tutorial and using the Weatherforecast .NET/Angular SPA from Visual Studio as a starting point for a project I plan to integrate SignalR with in the future. You can find the ...

The call to the Angular service has no matching overload between the two services in Typescript with 13 types

I encountered an error while creating a new Angular project following a tutorial, and I'm seeking assistance to understand it. The error message reads: "No overload matches this call. Overload 1 of 5... Type 'Object' is missing the followi ...

When using Material-UI with TypeScript, an error is thrown stating that global is not defined

After running the following commands: npm install --save react react-dom @material-ui/core npm install --save-dev webpack webpack-cli typescript ts-loader @types/react @types/react-dom I transpiled main.tsx: import * as React from "react"; import * as R ...

Creating Mongoose models in TypeScript with multiple connections

Attempting to build a model with multiple connections as per the documentation, I encountered the following error: TS2345: Argument of type 'Schema<Document<any>, Model<Document<any>>>' is not assignable to parameter of ty ...

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 ...

Tips for customizing the legend color in Angular-chart.js

In the angular-chart.js documentation, there is a pie/polar chart example with a colored legend in the very last section. While this seems like the solution I need, I encountered an issue: My frontend code mirrors the code from the documentation: <can ...

A guide on automatically focusing on a Material UI Formik form TextField using React and TypeScript

I'm attempting to automatically focus my textField, but the 'autoFocus' attribute only seems to work after I submit the form and add a value. If no values are added (i.e. when opening the miui modal for the first time), the autoFocus does no ...