Is there a way to simultaneously call two APIs and then immediately call a third one using RXJS?

I am looking to optimize the process of making API calls by running two in parallel and then a third immediately after both have completed. I have successfully implemented parallel API calls using mergeMap and consecutive calls using concatMap, but now I want to combine the two methods.

//Call API1 and API2 in Parallel
// from([apiCall(1), apiCall(2)]).pipe(
//   mergeMap(e=>e)
// ).subscribe(x => console.log(x));

//Call API1 and API2 consecutively
// from([apiCall(1), apiCall(2)]).pipe(
//   concatMap(e=>e)
// ).subscribe(x => console.log(x));

//Call API1 and API2 in Parallel and API 3 right after both finishes
from([apiCall(1), apiCall(2), apiCall(3)]).pipe(
  // ????
).subscribe(x => console.log(x));

Any suggestions on how to achieve this?

Check out the Stackblitz playground for experimentation: https://stackblitz.com/edit/playground-rxjs-263xwk

Answer №1

Implementing forkJoin allows for making parallel requests.

Using forkJoin to execute multiple API calls at once is a great way to improve performance and efficiency in your application.
Here's an example:
forkJoin([apiCall(1), apiCall(2)]).pipe(
 concatMap((response) => apiCall(3).pipe(
  map((res) => [...response, res])
 ))
).subscribe((response) => {
 response[0]; // result from apiCall(1)
 response[1]; // result from apiCall(2)
 response[2]; // result from apiCall(3)
})

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

Upon the second click, the addEventListener function is triggered

When using the window.addEventListener, I am encountering an issue where it only triggers on the second click. This is happening after I initially click on the li element to view the task information, and then click on the delete button which fires the eve ...

Getting the version from package.json in Next.js can be easily achieved by accessing the `version

In my quest to retrieve the "version" from the package.json in a Next.js application, I encountered a roadblock. I attempted using process.env.npm_package_version, similar to how it is done in a Node application, but unfortunately, it returned undefined. ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

Combining results from multiple subscriptions in RxJS leads to a TypeScript compiler error

I am utilizing an Angular service that provides a filterObservable. To combine multiple calls, I am using Rx.Observable.zip(). Although it functions as expected, my TypeScript compiler is throwing an error for the method: error TS2346: Supplied paramete ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

TypeScript's type casting will fail if one mandatory interface property is missing while an additional property is present

While running tsc locally on an example file named example.ts, I encountered some unexpected behavior. In particular, when I created the object onePropMissing and omitted the property c which is not optional according to the interface definition, I did not ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Taking advantage of Input decorator to access several properties in Angular 2

I am currently working on a component that is designed to receive two inputs through its selector. However, I would like to make it flexible enough to accept any number of inputs from various components. Initially, I tried using a single @Input() decorator ...

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Error encountered: The input value does not correspond to any valid input type for the specified field in Prisma -Seed

When trying to run the seed command tsx prisma/seed.ts, it failed to create a post and returned an error. → 6 await prisma.habit.create( Validation failed for the query: Unable to match input value to any allowed input type for the field. Parse erro ...

Exploring the potential of lazy loading with AngularJS 2 RC5 ngModule

I am currently utilizing the RC5 ngModule in my Angular project. In my app.module.ts file, the import statements and module setup are as follows: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/plat ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

Clicking the button in Angular should trigger a series of functions to be

It seems like I'm struggling with a simple question due to my lack of experience in this area. Any guidance or help would be greatly appreciated. I have a button that should trigger multiple functions when clicked, all defined in the same ts file. Wh ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

Revealing the Webhook URL to Users

After creating a connector app for Microsoft Teams using the yo teams command with Yeoman Generator, I encountered an issue. Upon examining the code in src\client\msteamsConnector\MsteamsConnectorConfig.tsx, I noticed that the webhook URL w ...

Understanding the data types of functions in TypeScript can be quite important for

What type of information is required after the colon : in this specific function? public saveHistory(log: String): "HERE!" { return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => { try { ...

Shuffle and Place indented list

I have a bunch of ideas and a list of projects. I need to choose one idea and match it with a project. I followed this guide to implement the drag and drop feature, but encountered an issue where every project gets assigned the same idea when dragging and ...