Problems with chaining observables in RxJS

Currently, I'm in the process of enhancing my code by utilizing merge map to call an observable within another observable.

Although the existing code functions properly, I recognize that it's not considered best practice. As a result, I am attempting to refactor it.

this._headerRefresh$.pipe(debounceTime(this.debounceTime)).subscribe(data => {
            this._outputProvider
                .getData(this.to.url, this.to.body ? this.to.body : undefined)
                .pipe(
                    debounceTime(this.debounceTime),
                )
                .subscribe(res => {
                    this.setstuff(res);
                });
        });

I attempted to refactor the code in the following manner, however, it appears that the 'this.setstuff(res)' is not being called as expected:

this._headerRefresh$
        .pipe(
          debounceTime(this.debounceTime),
          mergeMapTo(
            this._outputProvider
              .getData(this.to.url, this.to.body ? this.to.body : undefined)
          ),
        )
        .subscribe(res => {
          console.log(res);
          this.setstuff(res);
        });

Could there be something crucial that I have overlooked?

Answer №1

if this.to.url and this.to.body are constantly changing, using mergeMapTo won't work ... you should opt for mergeMap instead so they can be re-evaluated with each emission, rather than just once when the stream is initialized:

      mergeMap(() =>
        this._outputProvider
          .getData(this.to.url, this.to.body ? this.to.body : undefined)
      ),

you might also want to consider using switchMap or exhaustMap in place of mergeMap... as their behaviors differ slightly.

with mergeMap, every outer emission will trigger the inner observable, and all inner observables emitted will continue until completion. They will arrive in the order they were emitted, not necessarily in the order they were triggered by the outer observable. This could potentially lead to unnecessary HTTP calls at best, or result in receiving outdated data at worst.

on the other hand, with switchMap, new emissions will cause any prior active inner observables to cancel, switching to the new call instead.

For exhaustMap, it works inversely by ignoring outer emissions while there is an active inner observable. Although not commonly used, a common scenario would be for a refresh signal where you wouldn't want to restart the refresh process or trigger additional refreshes while one is already ongoing.

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

sendResponse' was not located

chrome.runtime.onMessage.addListener( function(props) { switch(props.request_type) { case 'msg': websocketClass.msgSubmit(props.data) break; case 'url': websocketClass.msgSubmit(props.data) break; case 'his': sendResponse({his ...

Error in Angular unit testing: Unable to access the 'subscribe' property as it is undefined

Currently, I am working on a starter kit template that includes authentication and an example with CRUD operations. You can find the code here: https://github.com/fransyozef/basic-login-angular Although I am new to unit testing, I am trying to set up test ...

Can TypeScript truly be considered backwards compatible?

Lately, I've been diving into Typescript as I have a huge Node.js Express Mongodb project that I'm thinking of converting from my current JS+Babel setup to Typescript. One confusing aspect for me is the claim that Typescript is backwards compati ...

What is the best way to access private properties within an extended Angular Component utilizing a directive?

I'm currently in the process of enhancing the functionality of the PoStepperComponent from the @po-ui/ng-components library within an Angular project. One specific requirement is to extend this component to introduce custom features. The plan entails ...

Utilizing TypeScript for dynamic invocation of chalk

In my TypeScript code, I am trying to dynamically call the chalk method. Here is an example of what I have: import chalk from 'chalk'; const color: string = "red"; const message: string = "My Title"; const light: boolean = fa ...

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

Accessing items in a list generated by ngFor in Angular 6 using checkboxes

I need help with displaying an array using ngFor in Angular (specifically Angular 6). I want to be able to select certain cars by checking a checkbox, and then purchase the selected cars when I press a button. Although the list and checkboxes display corr ...

I'm experiencing issues with my NgRx effects as they are not functioning properly and nothing

I'm facing an issue with my NgRx effects. Although the application successfully adds to the store, my effects related to the request are not executing. When adding a new car, it should be added to the store and trigger the effects, but nothing is hap ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

My approach to retrieving data from Firebase and converting it into an array of a specific type

Recently, I made the decision to expand my iOS application to also function as a web app. Although the implementation seems to be working, I am unsure if it is done correctly. I would appreciate it if someone could confirm if the implementation is correct. ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

Using Typescript: How to access a variable beyond the scope of a loop

After creating an array, I need to access the elements outside of the loop. I am aware that they are not in the scope and using 'this.' before them does not grant access. colIdx = colIdx + this.columns.findIndex(c => c.editable); this.focusIn ...

Errors occur with Metro bundler while utilizing module-resolver

Recently, I completed a project using the expo typescript template that runs on both iOS and Android platforms, excluding web. To enhance my development process, I established path aliases in the tsconfig.json file as shown below: "paths": { "@models/ ...

The Angular 2 routerLink doesn't update the component after the initial click, even though the URL changes in the browser

When using Angular 2, I encountered an issue where clicking a routerLink in the App module successfully navigates to a parameterised route (e.g. /events/2) and loads the correct component (event-details) on the initial click. However, subsequent clicks on ...

Which is better for Angular development - npm or Visual Studio Code?

When creating a UI project using Angular 6, I am at a crossroads. Should I start by creating an Angular project using npm or should I use the Visual Studio Angular template? The UI will be consuming Web APIs written in .NET Core 2.1. I experimented with b ...

Function that calculates return type dynamically based on the input array of keys

In my AWS lambda functions, I have a variety of modules like UserModule, NotificationsModule, CompanyModule, and more. To simplify the usage of these modules, I created an interface that outlines their structure as shown below: interface Modules { comp ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

What steps can be taken to ensure that a second Pinia plugin waits for the completion of the

I am currently developing a Vue application with Pinia as the state manager. I have created two plugins - one for authentication and another to set up my API instance. The second plugin relies on the token obtained from the first plugin. Upon analyzing th ...

Unleashing the Power of Firebase Service in Angular Components: A Guide to Effective Unit Testing

I am currently working on testing my Create-User-Component which relies on an Auth Service that includes methods like 'login, logout,' etc. The Auth Service imports both AngularFireAuth and AngularFirestore, and it is responsible for handling da ...

Adding a function to an interface in React Typescript: A step-by-step guide

My current setup is structured like this: enum AnimeType { Action = "ACTION" Comedy = "COMEDY" } const animeTypes: {[key: string]: AnimeInfo} = { "ACTION": { info: "Action-packed fun", co ...