Combine two streams under certain conditions using RxJs

When working with streams, I am facing a scenario where I have two server calls to make in order to get the required response. However, if the first call returns data, I do not want to execute the second call. I have been struggling to find the proper combination of operators to cancel the second request upon the success of the first one without throwing an error.

I attempted using defaultIfEmpty, but it felt like a hack and I was not satisfied with this approach.

I have prepared a StackBlitz example that you can view here. I am unsure if this is considered good practice or not. Essentially, what I need is a conditional concatMap.

If you are aware of how to achieve this using existing operators without creating new ones, I would appreciate hearing about your solutions and approaches.

Thank you in advance.

Answer №1

When dealing with async requests that are of type Observable<T> and only return a value T on success, you can simplify the process by using .concat():

firstAsyncCall()
  .concat(secondAsyncCall())
  .take(1)

By adding .take(1), you ensure that secondAsyncCall() will not be triggered if firstAsyncCall returns (at least) one value.

Answer №2

To halt the stream when a value no longer fits your criteria, utilize the filter function:

https://example.com/edit/typescript-abc123?file=index.ts

const interval$ = interval(100);

interval$.pipe(
  filter(val => val % 10 === 0),
  take(10),
).subscribe(val => console.log(val));

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

Error message in Angular2 for production build with webpack: "Unable to load app/app.component.html"

My current project is utilizing Angular2-webpack-starter, running on Angular2 rc.4 and webpack 1.13.1. Everything functions smoothly in dev mode. However, when attempting to switch to production mode, I encounter the error message Failed to load app/app.c ...

I encountered an issue with the date input stating, "The parameters dictionary includes a missing value for 'Fromdate' parameter, which is of non-nullable type 'System.DateTime'."

An error message is popping up that says: '{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'Fromdate' of non-nullable type 'System.DateTime' for method 'Syste ...

Sending a style prop to a React component

My typescript Next.js app seems to be misbehaving, or perhaps I'm just not understanding something properly. I have a component called <CluckHUD props="styles.Moon" /> that is meant to pass the theme as a CSS classname in order to c ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

Using Angular2 to Toggle Checkbox Field Enabled and Disabled

As I dynamically render checkbox and combobox fields, the following functionality is performed: If the checkbox field appears as selected based on the API response, then the combo box appears as enabled; otherwise, it would be disabled. If a user selects ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

Talebook: Unable to modify UI theming color

As I embark on creating my own theme in Storybook, I am closely following the guidelines outlined here: Currently, I have copied the necessary files from the website and everything seems to be working fine. However, I am facing an issue when trying to cus ...

Developing a unique TypeScript singleton pattern tailored for multiple PouchDB instances

I have developed a node application that interfaces with multiple databases. I've designed a class which allows me to create various databases effortlessly, as they share similar CRUD operations. The Class: class DatabaseService { private dbName: ...

What is the process for specifying an input for a component?

When defining an input for a component like this: @Input() person: Person, some encountered the error message saying, "property 'person' has no initializer and is not definitely assigned in the constructor" even though the Person model has been i ...

What could be causing my application to not locate the jquery module? ERROR: ENOENT: The specified file or directory cannot be found

I've decided to bring over an Angular project that already has a bootstrap template integrated into my own project. (Still unsure if this was the right move) One of the steps I took was adding these lines to the angular.json file: "styles": [ ...

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...

Guide on formatting the API response using a callback function in Angular development

How can I reformat my API response using a callback function and access the data within the angular subscribe method? I attempted to use mergemap but it didn't work as expected. this.http.get('https://some.com/questions.xml', {headers, res ...

The Angular2 project using ag-grid-enterprise is currently experiencing difficulties with implementing the License Key

I have a valid license for the ag-grid-enterprise version, but I'm struggling with how to integrate it into my Angular2 project. I've attempted placing the license in the main.ts file using LicenseManager and specifying the enterprise version in ...

The absence of @angular/compiler in the bundle file is causing an issue with Angular es

I've developed a shell application that operates using and https://github.com/systemjs/systemjs to manage its various micro-frontends. Recently, I created a new Angular application and aimed to integrate it with the esBuild builder tool. Upon runni ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Angular 7 and its scrolling div

Currently, I am working on implementing a straightforward drag and drop feature. When dragging an item, my goal is to scroll the containing div by a specified amount in either direction. To achieve this, I am utilizing Angular Material's CDK drag an ...

Creating specific union types for a bespoke React hook

There are 4 objects with both similar and different keys. The union of these objects is used for database operations as follows -> type Objects = Food | Diary | Plan | Recipe ; A Custom Pagination Hook function usePaginate (key: string, options: Option ...

I am experiencing issues with Angular routing as it keeps redirecting me back to the main base url

Currently, I am attempting to utilize the angular router in order to navigate from one page to another. Within my page, there is a button that, upon clicking, should direct me to a different page. At this moment, my URL reads as: http://localhost:4200/us ...

ngx-loading is a fantastic addition to Angular 7, ensuring that the spinner is continually visible

While using ngx-loading to display a spinner during server response retrieval, I encountered an issue. The spinner works properly by appearing when the request is sent and disappearing once the server response is received. However, if I click on the area w ...