How can I combine multiple requests in RxJS, executing one request at a time in parallel, and receiving a single combined result?

For instance, assume I have 2 API services that return data in the form of Observables.

function add(row) {
    let r = Math.ceil(Math.random() * 2000);
    let k = row + 1;
    return timer(r).pipe(mapTo(k));
}

function multiple(row) {
    let r = Math.ceil(Math.random() * 2000);
    let k = row * 10;
    return timer(r).pipe(mapTo(k));
}

Now, with an array [1, 2, 3, 4, 5], I am using the above functions in the following way:

from([1, 2, 3, 4, 5]).pipe(
        mergeMap((row) => {
            return add(row);
        }),
        mergeMap((row) => {
            return multiply(row);
        }),
        toArray()
    ).subscribe((_) => {
        console.log("sub", _);
    });

The resulting output is

sub [ 50, 20, 60, 40, 30 ]

This outcome meets my requirements. However, I am unsure about how to link the source elements from the array to their corresponding results.

I hope for a result like

[ [4, 50], [1, 20], [5, 60], [3, 40], [2, 30] ] 

or

[
  { sourceData: 4, result: 50 },
  { sourceData: 1, result: 20 },
  ...
]

If I use concatMap to maintain the sequence, the program will execute sequentially. However, I am more concerned with connecting the source and the result rather than preserving the order.

Thank you very much~

Answer №1

Is this approach worth a try?

  from([1, 2, 3, 4, 5]).pipe(
    mergeMap((row) => {
      const index$ = of(row);
      return forkJoin([index$, add(row)]);
    }),
    mergeMap(([index, row]) => {
      return forkJoin([of(index), mutiple(row)]);
    }),
    toArray()
  ).subscribe((_) => {
    console.log("sub", _);
  });

Alternatively,

  const handler = v => {
    return of(v).pipe(
      mergeMap((row) => {
        return add(row);
      }),
      mergeMap((row) => {
        return mutiple(row);
      }),
    )
  }

  from([1, 2, 3, 4, 5]).pipe(
    mergeMap(row => forkJoin([of(row), handler(row)])),
    toArray()
  ).subscribe((_) => {
    console.log("sub", _);
  });

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

I'm interested in learning how to implement dynamic routes in Nexy.js using TypeScript. How can I

I have a folder structure set up like this: https://i.stack.imgur.com/qhnaP.png [postId].ts import { useRouter } from 'next/router' const Post = () => { const router = useRouter() const { pid } = router.query return <p>Post: {p ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

Using regular expressions in Sublime Text 2 to replace text in JSON files can greatly improve your workflow

After using an online web tool to convert an Excel file to JSON, I now require assistance in replacing certain values within the JSON. Currently, I am using Sublime Text 2. {"Time (GMT-04:00)":"2010-07-06 08:30:00","Skin temp - average":"34,2043","Step Co ...

A guide on setting up dual observables in Angular 2

Currently, I am implementing Observable in angular 2 with rxjs. As part of my demonstration, I have utilized fromEvent in a Plunker. Here is the link to my demo: https://plnkr.co/edit/zkgEcdn21CvIKoOycUOy?p=preview In this demo, I have included two input ...

Exploring the Module System of TypeScript

I am working with a TypeScript module structured like this: let function test(){ //... } export default test; My goal is for tsc to compile it in the following way: let function test(){ //... } module.exports = test; However, upon compilation, ...

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

Creating synchronicity in your code within the useEffect hook

Is there a way to ensure that my function is fully completed before moving on, even though it's not recommended to add async to useEffect? Take a look at this code snippet: useEffect( () => { const RetrieverDataProcess = async () => ...

What are the benefits of using React.useMemo or React.useCallback within component props?

Exploring efficient ways to implement TailwindCSS in React, considering its utility-first nature leading to component-heavy code (e.g. className="w-full bg-red-500"). One approach is creating a utility function like: utils/tailwind.ts const tw = (...clas ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

Navigating with Reach Router only updates the URL, not the component being rendered

Is there a way to programmatically navigate using Reach Router in React? I have noticed that when updating the URL, the route does not render. Even though the URL changes, the original component remains displayed according to the React developer tools. Ho ...

Adding options to a dropdown menu dynamically while editing a form with the help of javascript

I have a dropdown like in below:- <form name="depositForm" action="<?php echo site_url('ajax_funds/deposit_funds'); ?>" id="depositForm" class="page-form-main form-horizontal " autocomplete="off" method="post"> <div class="form- ...

Different ways to resize an image in various sizes without relying on PHP thumb

I have developed an admin panel for managing reservations of charter, yacht and other vehicles. I am looking for a solution to upload only one image per vehicle and resize it in multiple sizes without relying on the phpthumb library due to its slow loadi ...

SignalR gets stuck on the 'Initiating start request' screen, halting all progress

SignalR has been causing some strange behavior for me lately. After doing some refactoring, I started experiencing connectivity issues. It seems like my code was just lucky to work before because it didn't follow the recommended practices. For example ...

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...

What is the recommended approach for managing state in React when multiple components are trying to access and modify its data at the same time?

Issue: I am experiencing difficulty in adding new keys and/or values to the JSON editor or YAML editor when they both share and update the same state. The parent component sends JSON data to the child component through props import * as React from 'r ...

You can't observe the behavior of simulated functions in a class with a manually created mock

Kindly note that I have set up a comprehensive Github repository where you can download and explore the content yourself here I am currently working on mocking a non-default exported class within a module using a manual mock placed in the folder __mocks__ ...

How can I efficiently generate a table using Vue js and Element UI?

I am utilizing element io for components. However, I am facing an issue with printing using window.print(). It currently prints the entire page, but I only want to print the table section. ...

Unable to activate parameter function until receiving "yes" confirmation from a confirmation service utilizing a Subject observable

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One of the unit tests involves opening a modal and removing an item from a tree node. Everything goes smoothly until the removeItem() function is called. This functi ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...