Is it possible to use two mergeMap operators concurrently in RxJs?

Recently, I started using RxJs alongside redux and have successfully created a working stream. Below is the code snippet of my action pipe:

action$.pipe(
            ofType(DELETE_CALL_HISTORY),
            withLatestFrom(state$),
            mergeMap(() =>
                fromPromise(accessService.getCallHistory()).pipe(
                    mergeMap((res: any) => of(deleteCallHistory(res))),
                    mergeMap((res: any) => of(setCallHistory(res.param))),
                    catchError((err: any) => {
                        console.error(err);
                        return of(
                            showErrorAndHideAfterDelay({
                                message: err,
                                label: 'Error',
                            }),
                        );
                    }),

                ),
            ),
        ),

In this implementation, I am attempting to execute three actions. The getCallHistory action is responsible for fetching data initially. Next, the deleteCallHistory action aims to remove an item from the list. So far, the action pipe functions as expected. However, when trying to utilize the setCallHistory action to set the updated list, it does not produce the desired result. Although the setCallHistory action is triggered, deleted items reappear upon app reload. Should I be duplicating the use of mergeMap like this or is there another approach I should consider?

Answer №1

Important note for your code:

  // ...
  mergeMap((res: any) => of(deleteCallHistory(res))),
  // The pipeline now contains the response from deleteCallHistory
  mergeMap((res: any) => of(setCallHistory(res.param))), 
  //...

Have you remembered to wrap the API calls with fromPromise?:

  // ...
  mergeMap((res: any) => fromPromise(deleteCallHistory(res))),
  // The pipeline now contains the response from deleteCallHistory
  mergeMap((res: any) => fromPromise(setCallHistory(res.param))), 
  //...

If you need to execute multiple API calls in sequence, consider using concat:

  import { concat } from 'rxjs';
  // ...
  mergeMap((res: any) => concat(
    of(deleteCallHistory(res)),
    of(setCallHistory(res.param))
  ),
  //...

If you need to execute multiple API calls in parallel, consider using merge:

  import { merge } from 'rxjs';
  // ...
  mergeMap((res: any) => merge(
    of(deleteCallHistory(res)),
    of(setCallHistory(res.param))
  ),
  //...

Answer №2

What is the reason for invoking mergeMap and using of internally?

These two approaches are almost identical:

mergeMap((res: any) => of(deleteCallHistory(res)))
map((res: any) => deleteCallHistory(res)))

Both will forward the outcome of deleteCallHistory down the stream. The issue most likely lies there. If deleteCallHistory returns an observable, it will not be executed as the result is an observable nested within another observable due to of.

Therefore, if deleteCallHistory returns a promise or observable, you can simply use mergeMap without wrapping deleteCallHistory in anything:

mergeMap((res: any) => deleteCallHistory(res))

This situation could also arise when calling setCallHistory. If you do not need to propagate the result from it, you can utilize tap or do. Additionally, if it returns an observable or promise, avoid using of.

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

What is the reason behind having to press the Tab button twice for it to work?

Currently, I am implementing a Tabbed Form with jQuery Functionality in Angular 4. The Tabbed Form itself is functioning, but I've noticed that I have to click the Tab Button twice for it to respond. See the code snippet below: TS declare var jquery ...

Problem with file organizer in Angular application - unable to see files and directories

I successfully integrated a file manager component following this tutorial. Despite no errors in vscode or chrome debug tool, my folders are not visible. Can anyone help me troubleshoot this issue? https://i.stack.imgur.com/ihEak.png I am unsure how to r ...

Directly within Angular, map the JSON data to an object for easy assignment

I came across this information on https://angular.io/guide/http. According to the source, in order to access properties defined in an interface, it is necessary to convert the plain object obtained from JSON into the required response type. To access pr ...

Error alert: The return type is missing in the array.map method

After running ESLint on my TypeScript code, I received a warning that says: "Missing return type on function.eslint(@typescript-eslint/explicit-function-return-type)". The warning specifically points to the lambda function within the map function. privat ...

Ways to efficiently transmit pre-designed HTML components from a WebMethod to jQuery

I'm currently working on implementing infinite scrolling on my ASP.NET C# Website. In the past, I used a somewhat cumbersome method involving the ListView Control to achieve lazy scrolling, but I'm looking for a more efficient solution this time. ...

Restangular failing to apply headers during post requests

I have been encountering an issue while trying to set the header for a single post request using Restangular. Despite following the documentation here and seeking help from a similar question, the request is being sent as plain text instead of JSON. My se ...

(perhaps) just a question regarding AJAX and PHP

Having a bit of trouble here - I have two files, main.html and processing.php. In the php file, I am trying to update a specific element on main.html, but I can't seem to retrieve either the html or javascript value from main.html For instance, main. ...

Retrieve the structure from a React application

When it comes to documenting architecture, the process can be incredibly beneficial but also quite time-consuming and prone to becoming outdated quickly. I have come across tools like Doxygen that are able to extract architectural details such as dependen ...

Utilize Function type while preserving generics

Is there a way in Typescript to reference a function type with generics without instantiating them, but rather passing them to be instantiated when the function is called? For instance, consider the following type: type FetchPageData<T> = (client : ...

The TypeScript error message reads: "You cannot assign type 'undefined' to type 'ReactElement'."

I'm encountering an error in my react project TypeScript error Argument of type 'ReactNode' is not compatible with parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactElement<any, string | JSX ...

What is the process for invoking a JavaScript function and storing form data in a text file within an HTML document?

My HTML code is here..... <!DOCTYPE html> <html> <title>Plot</title> <head> <script type="text/javascript" src="d3.min.js"></script> <script> function filter() { var choice = document.ge ...

Prevent the function from affecting type deduction

I am working with a type similar to this: interface Test<R, T> { inputType: R; transformer: (input: R extends any ? R : never) => T; } // function for inferring type function inferTest<T extends Test<any, any>>(t: T): T { ...

react router 2 will display a 404 error when the requested page is not

Currently, I am utilizing react router version 2.8.1 and attempting to configure my custom 404 page for my single-page application (SPA). However, I am encountering issues in actually returning a proper 404 status code. My main goal is to prevent Google fr ...

Incorporate a personalized menu into the FullPage.js section

Seeking advice on fullpage.js for my website - Can a non-sticky menu be added to all sections without affecting loading speed? I attempted to include the menu code in each section, but it slowed down my website. Any suggestions or tips? ...

Utilizing Azure Function Model v4: Establishing a Connection with Express.js

Using Model v4 in my Azure function index.ts import { app } from "@azure/functions"; import azureFunctionHandler from "azure-aws-serverless-express"; import expressApp from "../../app"; app.http("httpTrigger1", { methods: ["GET"], route: "api/{*segme ...

create-react-app is displaying an error message stating, "In order to utilize this application, JavaScript must be enabled."

I am using express to build my API. Within my project, I have a folder named app and another named server. The app folder serves as the client application, built with create-react-app as the boilerplate, while the server folder contains the express.js app ...

"Unveiling the mystery of ejs form submissions with undefined values

I'm facing a bit of difficulty and need some guidance. I am attempting to develop a URL shortener using Node, Express, and Ejs. However, I'm encountering an issue where my EJS form is sending undefined values. Below is the snippet of my EJS code ...

Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below. This code is using rxjs 5.0.3 with tsc 2.1.5 import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject ...

Is there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...

convert json formatting to a string

Can anyone assist me in resolving this issue? I am trying to achieve the following format: true: 2,3,4 false: 5 I am using sequelize, I am struggling with outputting JSON correctly Please see my code snippet below. However, it is not functioning as ex ...