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

How to transfer files between Dropbox and AWS S3 using Angular 5

Currently, I'm utilizing the Dropbox file picker to download a file. Once a file is selected using the Dropbox picker, I obtain the download link. I'm wondering if it's possible to save it as a bytestream in the browser and then upload it t ...

How to toggle the display of a div by its id using index in Javascript

Currently, I am encountering a problem with toggling the div containers. When I click on the video button, I want the other divs to close if they are already open. However, due to the toggling mechanism, if a div is closed and I click on the corresponding ...

Exploring Angular 2: Incorporating multiple HTML pages into a single component

I am currently learning Angular 2 and have a component called Register. Within this single component, I have five different HTML pages. Is it possible to have multiple templates per component in order to navigate between these pages? How can I implement ro ...

Angular displays incorrect HTTP error response status as 0 instead of the actual status code

In Angular, the HttpErrorResponse status is returning 0 instead of the actual status. However, the correct status is being displayed in the browser's network tab. ...

Creating a welcome screen that is displayed only the first time the app is opened

Within my application, I envisioned a startup/welcome page that users would encounter when the app is launched. They could then proceed by clicking a button to navigate to the login screen and continue using the app. Subsequently, each time the user revisi ...

Exploring the power of query parameters in Ionic 4

Currently, I am in the process of transitioning a web-based Ionic 3 project to Ionic 4. Upon scanning a QR code, a page is supposed to open with a URL structure like this: domain.com/qanda/pwa/home?user=simon&skill=ionic&role=Admin&Table=132 ...

AWS Amplify is failing to maintain the user session post a successful login

Currently, I am developing an aws-serverless application using React. My main issue lies in the authentication process with aws-amplify. The authentication works smoothly, but the session is not being preserved. During the signing-in stage: await Auth.s ...

Tips for testing validation messages in Angular template-driven forms

I have created a simple Angular template-driven form with one required field. An error message is supposed to be shown if the field is not valid, such as when the component is initially loaded and the required field is empty. The code functions correctly i ...

What is the best way to expand and collapse a mat-expansion-panel using a button click

Is it possible to expand a specific mat-expansion-panel by clicking an external button? I've attempted linking to the ID of the panel, but haven't had any luck... <mat-expansion-panel id="panel1"> ... </> ... <button (click)="doc ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Fixed headers remain in place as you scroll horizontally on a single table

Within my system, I have organized two tables: table one and table 2 are stacked on top of each other. I've managed to freeze the column headers so that they are displayed vertically, remaining static as users scroll horizontally. To achieve this effe ...

When attempting to update to Angular Material 8 using ng update, I ended up with @angular/* version ~9.0.0-next-0. Can anyone explain why there is this

While attempting to upgrade my Angular 7 application to Angular 8 using the instructions provided here, I encountered an issue with the last step: ng update @angular/material After running this command, the Angular Material packages were successfully u ...

What steps should I take to manage an error image that is not found in a directory on my computer?

I am currently working with a list that displays various information, along with an image search function in an img tag that looks for a specific image related to the information. However, some of the information does not have a corresponding image and I w ...

The primary route module is automatically loaded alongside all other modules

I have configured my lazy loaded Home module to have an empty path. However, the issue I am facing is that whenever I try to load different modules such as login using its URL like /new/auth, the home module also gets loaded along with it. const routes: R ...

Encountering the error "Object potentially undefined" while attempting to activate Cloud Function during document creation

My goal is to automatically create a new authenticated user whenever a new document is added to the "users" collection. The necessary user details will be extracted from the fields "email" and "phone" in the new document. The challenge I am facing is that ...

"Continue to shine until the rendering function displays its source code

I've encountered a strange issue where I'm using lit until to wait for a promise to return the template, but instead of the desired output, the until's function code is being rendered. For example: render() { return html` <div c ...

Accessing URL fragments in Next JS with context during the execution of getServerSideProps

I am trying to extract a URL fragment using getServerSideProps. The URL is structured like this: http://localhost:3000/some-folder#desiredParam=value Even though I pass the context as an argument to the getServerSideProps function, I am struggling to retr ...

Tips for preventing redundancy in Angular 2 form code

When developing my reactive forms, I always make sure to include specific properties and methods: @Input() public form: FormGroup; public messages = VALIDATION_MESSAGES; @Output() public onFormSubmit: EventEmitter<any> = new EventEmitter ...

The cloud function that is callable is currently inactive and encountering errors upon invocation

I am experiencing issues with my Cloud Function which is supposed to call a request to the URL passed to it. This is my first time using TypeScript to make a request, so I added some print calls to troubleshoot the problem. However, the first log never app ...

Leverage the key-value pairs in JSON to automatically suggest types within the function parameters

If we have data structured like this: { "key1": "hardcoded string", "key2": "another hardcoded string", } Imagine a function with 2 parameters where the first parameter should refer to key1 and the second to i ...