What is the best way to handle a promise passed as parameters to a Subject in RxJS?

When passing a Promise to Subject as a parameter:

const work = new Subject<{ id: number; dialogRef: Promise<typeof Dialog> }>();

I aim to utilize the instance inside the promise at a later stage:

...
exhaustMap(({ id, dialogRef }) =>
  http.get({ id }).pipe(tap(() => dialogRef.close()))
)
...

The issue arises because dialogRef is a Promise, requiring resolution before utilizing the instance function (close()).

While one way to achieve this is using async await, I am seeking an alternative to solve this using the "rxjs" approach.

I am in search of an operator or function that can resolve the promise and pass it to the exhaustMap operator, similar to:

 resolve(({ dialogRef }) => dialogRef),
 exhaustMap(({ id, dialogRef }) => //<-- dialogRef is NOT promise. it's instance
      http.get({ id }).pipe(tap(() => dialogRef.close()))
 )

Is it possible to achieve this with rxjs?

stackblitz

import { of, Subject } from 'rxjs';
import { exhaustMap, tap } from 'rxjs/operators;
console.clear();

const http = {
  get: ({ id }) => of(`data: ${id}`),
};

const Dialog = {
  close: () => {
    console.log('in close!');
  },
};

const work = new Subject<{ id: number; dialogRef: Promise<typeof Dialog> }>();

work
  .pipe(
    exhaustMap(({ id, dialogRef }) =>
      http.get({ id }).pipe(tap(async () => (await dialogRef).close()))
    )
  )
  .subscribe((r) => {
    console.log({ r });
  });

work.next({ id: 1, dialogRef: Promise.resolve(Dialog) });

Answer №1

Is this how it's done? https://example.com

performAction.pipe(
    switchMap(({ details, dialog }) => combineLatest({ details: of(details), dialog })),
    mergeMap(({ details, dialog }) => fetch.data({ details }).pipe(tap(() => dialog.close())))
).subscribe(...);

Answer №2

To utilize the concat function, follow this example:

work.pipe(
  exhaustMap(({id, dialogRef}) => concat(http.get(id), dialogRef.close()))
).subscribe()

If you wish to execute dialogRef.close after http.get, simply include defer for it:

work.pipe(
  exhaustMap(({id, dialogRef}) => concat(
    http.get(id),
    defer(() => dialogRef.close())
  ))
).subscribe()

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

The integration of a Bootstrap modal within the side bar's rendering

Struggling with a modal appearing inside my side div and can't find any solutions in the bootstrap5 documentation or online forums. https://i.stack.imgur.com/gHsBi.png I just want the modal to display centered on the page with the background fade ef ...

Using Multithreading and the Subscribe/Publish Methodology in JavaScript

Is it true that JavaScript does not support multithreading? I am seeking expert advice on a specific scenario. I need to make an AJAX call and upon successful completion, trigger a set of events to update different parts of the UI simultaneously. Would ...

What is the best approach for creating a brute-force solution for finding the smallest change algorithm

Looking for a solution to this algorithm challenge: Create a function that can determine the minimum amount of change that cannot be made with the given coins. function nonConstructibleChange(coins) { coins = coins.sort((a, b) => a - b); // O(nlogn) ...

How can Vue FullCalendar be configured dynamically?

I am trying to dynamically change some options in Vue FullCalendar, but the calendar is not applying them. You can check out my example here. The button at the bottom should set the maxTime option from 20:00 to 18:00. Is there a way to refresh the calen ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Respond to adjustments in iframe height

I am currently working on a page with an embedded iframe. The height of the iframe may change dynamically while on the page. I am wondering if there is a way to adjust the height of the iframe based on its content. Even after trying to set the height at ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

The Chartjs bar graph fails to display data upon initial page load

My HTML page includes a bar chart created using the ChartJS library. However, upon loading the page, the chart appears empty without displaying the data I provided and without rendering the bars. It only responds after clicking on the legend - first displa ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

Utilizing custom form fields with JavaScript in Symfony2

Here is my form field template: {% block test_question_widget %} {% spaceless %} <div {{ block('widget_container_attributes') }}> {% set type = type|default('hidden') %} <input type="{{ typ ...

Performing a Jquery ajax post to an MVC2 action

I have a script set up to send a POST request to an endpoint, and it seems like the routing is correct as it hits the breakpoint on the server. $(document).ready(function() { var o = new Object(); o.message = 'Hi from the page'; $.ajax({ ...

Mastering the art of looping through JSON values using AngularJS ng-repeat

Is there a way to use ng-repeat in order to iterate and access the name values: test01, test02, and test03 from my JSON data? Any guidance on how to achieve this using ng-repeat would be greatly appreciated. Thanks in advance! Check out this Fiddle link. ...

What could be causing the onclick function to not activate on the iOS safari browser?

My Shopify site works perfectly on all browsers except iOS Safari. When users try to click the "add to cart" button on this specific browser, it does not trigger the onclick function. This issue is unique to iOS Safari as the button works fine on desktop a ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

It seems that the JavaScript object is producing varied values in distinct locations despite no alterations made in between

I've encountered a puzzling issue where a variable is returning different values within a function, despite no modifications being made to it. This problem arises in a form component created using Vue.js (v2) that triggers a Vuex action. While I beli ...

Perform an action when a button is clicked in a VueJs single-page application

How can I trigger the refreshMailList function when clicking on the mail-list component? This is my Vue instance with a custom mail-list component: Vue.component('mail-list', { props: ['inboxmail'], template: ` <div> ...

Converting dates in Javascript

I have retrieved a date/time value of "20131218" from an API response. My goal is to transform this date into the format "2013-12-18". In PHP, this can be easily achieved with the following code: echo date("Y-m-d", strtotime('20131218')); The ...

Embracing the beauty of incorporating nested quotations

I've been experimenting with jquery's append functions lately. I'm adding a substantial amount of html, specifically a button with an onclick event function. It might sound complicated, but due to some technical restrictions, this is my onl ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

Scrolling the Ionic framework to a position below zero

My ion scroll is synchronized with another component for scrolling. I achieve this by using the function scroll1.scrollTo(left, top, false); Unfortunately, this function does not allow scrolling to a negative position, such as scroll1.scrollTo(left, -50, ...