Using RxJS subjects to switch maps and call another observable

Whenever a value is emitted in the subject, I want to call another observable.

The issue I am currently facing is that when the first value is emitted to the subject, it triggers the switchMap and calls the confirmCsvUpload(...) function. However, subsequent values trigger the switchMap but not the confirmCsvUpload(...) function.

I am seeking assistance in understanding why the function is not being called.

// Definition of Subject
private _confirmCsvUpload = new Subject<{ account: Account, previewData: PreviewData[], previewId: string }>();

// Subscription to the Subject 
this._confirmCsvUpload.pipe(
  switchMap(previewData => this._uploadCsvService.confirmCsvUpload(previewData.account, previewData.previewData, previewData.previewId))
).subscribe();

// Function that emits a value to the subject (This is not the function that is called in the switchMap())
confirmCsvUpload(): void {
  this._confirmCsvUpload.next({ account: this.account, previewData: this._previewData, previewId: this.getPreviewIdFromRoute() });
}

Answer №1

Here is the code snippet that tries to simulate a scenario:

  private _confirm$ = new Subject();
  private _destroy$ = new Subject();
  
  ngOnInit() {
    this._confirm$
      .pipe(
        takeUntil(this._destroy$),
        tap((value) => console.log('[SUB]', value)),
        switchMap((value: any) => this.secondCall())
      )
      .subscribe();
  }

  secondCall() {
    console.log('[SECOND CALL]');
    return of();
  }

  callSub() {
    console.log('[NEXT VALUE]');
    this._confirm$.next('value');
  }

  ngOnDestroy() {
    this._destroy$.next(null);
    this._destroy$.complete();
    console.log('[NG ON DESTROY]');
  }

The console log output for 2 calls would be:

[NEXT VALUE]
[SUB] value
[SECOND CALL]

-- on the second time:

[NEXT VALUE]
[SUB] value
[SECOND CALL]

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

Guide to creating an Express + TypeScript API using an OpenAPI 3.0 specification

After creating specifications for my REST API server using OpenAPI 3.0, I found myself wanting to generate an expressjs app quickly instead of manually writing repetitive code. However, the generated code from editor.swagger.io is in javascript, which does ...

Why Bootstrap 4 collapse feature is not functioning correctly within a ReactJS map component?

I am currently working on a project that requires implementing a collapse feature. The idea is to display all available content when the user clicks the Read More button (which is functioning as intended for collapsing). However, I am facing an issue where ...

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...

Fixing Firebase and React errors in JavaScript functions

Thank you for your understanding. I am currently integrating Firebase into my website. However, when I invoke the signup function in FormUp.js (which is declared in AuthContext.js), it does not reference the function definition. As a result, the function c ...

Restrict the PHP generated Json response to display only the top 5 results

I need to modify my search bar so that it only displays the top 5 related products after a search. public function getProducts() { if (request()->ajax()) { $search_term = request()->input('term', ''); $locatio ...

Highlighting JavaScript code with React Syntax Highlighter exclusively

I've been struggling to highlight Ruby code, but it seems like no matter what I do, it keeps highlighting JavaScript instead. It's frustrating because I can't seem to get it right. import React from "react"; import atom from "node_module ...

What is the most effective way to alter the text color using jQuery?

Whenever I want to create a text hover animation, jQuery is my go-to tool. Is there a snippet of code that can change the color or size of the text in this case? ...

Utilizing Flask to gather information from a leaflet map

I am currently working on creating a webpage using Flask. The webpage features a leaflet map where users can click to create a marker that opens a popup window with a link. The link's purpose is to open a new page displaying the longitude and latitude ...

What is the best way to choose the final index value in a drop-down menu?

Is there a way to read and select the last index value in a drop-down using JavaScript? Here is an example of the HTML code: <select name="unqiue"> <option value="number:1" label="1">1</option> <option value="number:2" label="2" ...

Tips for performing a custom atomic update on a mongodb document

While MongoDB does offer the ability to perform atomic updates using findOneAndUpdate, it is limited to basic operations such as set or increment. What I really need is a way to apply a custom function to transform my document: const updateDoc = async (e ...

Executing JavaScript files stored on my server using the Node.js command line interface

I need guidance on configuring an app that relies on running node generate.js and node generate_texts_index.js in the command prompt. These files are essential for building the necessary data for the app to function correctly. Running these files locally a ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

Obtain the text content within a textarea using jQuery

There is a text area that includes both html and regular text, and I need to extract both from the text area. However, it seems that the current code is only retrieving the html code. HTML CODE <textarea id='post'> <div class="separato ...

The dropdown consistently shows a value of zero

I am toggling the visibility of a div based on the selection from a Dropdown menu, but for some reason, the dropdown is consistently returning a value of 0. $(document).ready(function() { $('#rel_status').on('change', function() { ...

The function getoffer does not exist

I am encountering an issue with my factory declaration for Malls. It seems that I am getting the error message get offer is not a function! .controller('confirmCtrl', function($scope,Malls,$stateParams,$log) { $scope.offers = Malls.g ...

The ngx-translate/core is throwing an error message that says: "HttpClient provider not found!"

I recently downloaded the ngx-translate/core package and have been diligently following the provided documentation. However, I'm facing an issue with getting the translations to work. Here are the steps I've taken: 1] Definition in the AppModul ...

Attempting to hash the password led to encountering an error

An issue was encountered: both data and salt arguments are required. This error occurred at line 137 in the bcrypt.js file within the node_modules directory. The code snippet below highlights where the problem is present: const router = require("express" ...

What could be the reason for Next.js failing to retrieve client-side data following TypeScript validation and submission to the backend?

I am new to programming and encountering an issue with fetching data from MongoDB in my Next.js application. The client side appears to be working fine, and I have thoroughly reviewed the console logs and schema validation. Furthermore, I have implemented ...

Using Angularjs to dynamically generate and submit tables

I can't seem to figure out this specific situation Data: $scope.MyItem = [ { "__v": 0, "myItemId": "55ed819caefe18e81ffbd2d2", "itemId": "56fec8abb192c870117ed393", "january": 1, "february": 1, ...

Testing the addition of a dynamic class to an HTML button using Jasmine unit tests

I am brand new to Jasmine and currently in the process of grasping how to write Unit tests for my components in Angular 4. One issue I encountered is when I attempt to add a class to the button's classList within the ngOnInit() lifecycle hook of the C ...