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

Is it possible to stop Angular requests from being made within dynamic innerhtml?

I have a particular element in my code that looks like this: <div [innerHtml]="htmlContent | sanitiseHtml"></div> The sanitiseHtml pipe is used to sanitize the HTML content. Unfortunately, when the htmlContent includes relative images, these ...

React.js - Issue with table not being redrawn after data filtering

I am encountering an issue with my table in Next.js where the text input is not triggering a redraw. The expected behavior is to update the table with a single search result, but currently only the top row reflects the search result. Below is my useEffect ...

Ways to verify the presence of isBrowser in Angular 4

Previously, isBrowser from Angular Universal could be used to determine if your page was being rendered in a browser (allowing for usage of features like localStorage) or if it was being pre-rendered on the server side. However, it appears that angular2-u ...

Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project. As part of my work, I need to make an API call and perform various operations on the received data: public data_Config: IConfig[] = []; this.getService.Data(input).sub ...

Can a form be submitted using ViewChild in Angular5?

Can a form be submitted using ViewChild in Angular5? If so, how can it be achieved? I attempted to do this but was unsuccessful My Attempt: <form #form="ngForm" (submit)="submitForm(form)" novalidate> <input required type="text" #codeReques ...

Creating a cohesive "notification" feature in React with TypeScript that is integrated with one specific component

I am currently working on designing my application to streamline all notifications through a single "snackbar" style component (utilizing the material UI snackbar component) that encompasses the entire app: For instance class App extends React.Component ...

Sharing packages within nested scopes

Using @organization-scope/package/sub-package in npm is what I want to achieve. Here is my package.json configuration:- { "name": "@once/ui", ... ... } If I try the following:- { "name": "@once/ui/select-box", ... ... } An error pops up st ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

Unable to circumvent the Angular sanitize security measures

Using a wysiwyg editor (angular-editor): <angular-editor [(ngModel)]="code" name="code"></angular-editor> Underneath the editor, attempting to implement ngx-highlightjs: <pre> <code [highlight]="code" [lineNumbers]="true"></ ...

How can we declare and showcase a generic object with an unspecified number and names of keys in React using TypeScript?

I am facing a challenge with objects that have a 'comments' field. While all the other fields in these different objects have the same types, the 'comment' field varies. I do not know the exact number or names of the keys that will be p ...

Error: Model function not defined as a constructor in TypeScript, mongoose, and express

Can anyone help me with this error message "TypeError: PartyModel is not a constructor"? I've tried some solutions, but now I'm getting another error as well. After using const { ... } = require("./model/..."), I'm seeing "TypeError: C ...

Following the Angular 6 update, a new error message "Error: Expected to find an ngsw-config.json configuration file" appears when running the ng build --prod command

After completing the update process, I encountered an issue during the build where the following error message appeared. Error: Expected to find an ngsw-config.json configuration file in the /Users/nathanielmay/Code/firebaseTest folder. Either provide ...

Angular interceptor allows the execution of code after the outgoing request has completed its process

In the process of creating a simple interceptor, I have encountered an issue. The interceptor is designed to check if an outgoing request is targeting a specific endpoint type, namely events and favoriteevents. While the interceptor works almost as intend ...

Error message displayed: "There was an issue locating (undefined) and (undefined) while attempting to run Angular-CLI command 'ng g c my-new-component'."

Issue: I'm experiencing a problem in my Angular 5+ app project. When I try to generate a new component in one of my subfolders using the command ng g c my-component, nothing is being generated. Instead, I am encountering some unknown errors. I have a ...

What causes the ngIf directive to update the view of an HTTP observable only upon reloading the page?

Presently, I am utilizing a template: <div *ngIf="(currentUser | async)?.can('book')">Book Now</div> accompanied by its component: readonly currentUser: Observable<CurrentUser>; constructor(private userService: UserSe ...

What is the best method for comparing arrays of objects in TypeScript for optimal efficiency?

Two different APIs are sending me arrays of order objects. I need to check if both arrays have the same number of orders and if the values of these orders match as well. An order object looks like this: class Order { id: number; coupon: Coupon; customer ...

Developing dynamic-sized tuples in TypeScript

Recently, I was attempting to develop a zipper for arrays. For instance, if the user inputs 3 arrays with sizes of 3, 5, and 12, the output array of tuples would be the size of the largest array. The output consists of tuples containing elements at a speci ...

Navigating Using URL Paths in Angular 2 Application

I have my Angular 2 application hosted on an S3 server. Here is how the routing file is set up: const APP_ROUTES: Routes = [ { path: 'checkout', component: CheckoutComponent }, { path: 'thankyou', component: ThankyouComponent }, ...

Twilio CORS Angular HttpClient Integration

Currently attempting a "GET" request to the Twilio API using HttpClient module import { HttpClient } from '@angular/common/http'; Utilizing Angular CLI: 6.0.8 Node: 8.11.3 OS: darwin x64 Testing in both Firefox and Chrome, but running into th ...