Utilizing RxJS to maintain the value and seamlessly transition to a new one with switchMap

// Ticker data will be updated every 3 seconds
// Show hand action will only trigger after user clicks a button
// When the user clicks the button, I want to use the last ticker price as the order price

let lastPrice: number;

this.ticker$
  .do(ticker => lastPrice = ticker.closePrice)
  .switchMap(() => this.showHand$)
  .subscribe(showHand => {
     this.order.price = lastPrice;
     this.order.amount = showHand.amount;
     this.order.type = showHand.type;

     this.submit();
  });

Any suggestions on how to preserve value and switch map together without using a one-line variable like above?

Answer №2

To achieve the desired functionality, you can utilize a custom overload of SwitchMap, incorporating a selector function that combines both the outer and inner values:

this.ticker$
  .switchMap(
    () => this.showHand$,
    (tickerValue, switchMap) => tickerValue
  )
  .subscribe(showHand => { });

Answer №3

If you want to achieve this particular functionality, an interesting workaround is to create a new observable within the switchmap operator. This new observable can access the value passed into the switchmap function and then use it within an inner map to retain the original value.

this.ticker$
  .switchMap(ticker => this.showHand$.pipe(map(hand => ({ ticker,hand }) ))
  .subscribe( obj => {
     // utilize the value here
     this.order.price = obj.ticker;
     this.order.amount = obj.hand.amount;
     this.order.type = obj.hand.type;

     this.submit();
  });

Answer №4

This is my take on the code:

this.showHand$.take(1)
  .withLatestFrom(this.ticker$)
  .subscribe(([showHand, ticker]) => {
    this.order.price = ticker.closePrice;
    this.order.amount = showHand.amount;
    this.order.type = showHand.type;
    this.submit();      
  });

Remember, using take(1) will close the subscription. If you want to allow the user to press the button multiple times, save the subscription to a constant and unsubscribe when necessary.

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

Building a dynamic AngularJS module on-the-fly: A step-by-step guide

I am trying to dynamically create AngularJS modules, and here is what I have so far: <section class="panel portlet-item" id="crashpanel"></section> <script type="text/javascript"> var angularApp = angular.module("Crashpanel", []); angula ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

Mongoose Error: Typescript String Error: 'not assignable to type 'string'

I need help with setting up a logout route in my express backend. The idea is that when a user logs out, their JWT token should be stored in a blacklist Mongo database to prevent reusing the same token for login. The issue I'm facing is an error rela ...

What is the best way to convert all JS, CSS, and IMG files to a static subdomain

Here are some files that I have: sub.domain.com/js/test.js sub.domain.com/image1.jpg sub.domain.com/test.css I want to rewrite all these file types to start with: static-sub.domain.com/.... Can you help me with this? Thank you. ...

Guide to authenticating a Bearer token using a .pfx certificate and password in a NodeJs environment

I have successfully verified a token using a secret with the code below. Now, I need to verify the token using a .pfx certificate and password. How can this be done? jwt.verify(token, secret, options, function(err, decoded) { ... }); ...

Error message: "jQuery DataTables not working - table disappears when modal window opens

Currently working on an asp.net mvc application that utilizes the datatables grid. The grid is displayed and I have added a rowclick event to it: function CreateRowClickHandler() { var table = $('#table').dataTable(); $("#table > tbody").on(& ...

The issue of receiving an undefined JSON response persists in an AJAX file upload scenario

Currently, I am utilizing Valum's Ajax File uploader for handling same-page file uploads. The issue I'm facing is that despite numerous attempts and variations in my script, I consistently receive "undefined" when trying to access responseJSON[&a ...

How to Display Graph Horizontally using jqBarGraph

I have encountered a minor but significant issue while using jqBarGraph. Due to the limited space available for displaying the graph (550px width with unlimited height), and up to 50 items can be shown at once, the bars appear quite small (around 5px thi ...

Using Javascript to access element that was dynamically created by using getElementById

Exploring Javascript has been a fun hobby of mine, but I've hit a roadblock when trying to access dynamically created elements with another function. Here's the scenario: I have a link that generates dropdown selects with options when clicked. T ...

Tips for implementing conditional app.use() in nestJS backend strategies?

Trying to incorporate helmet into my nestJS application. I also require the inclusion of graphqlUploadExpress. How can I properly utilize the usesUpload condition to implement either helmet alone or along with upload? import { NestFactory } from '@nes ...

ag-grid renderer displays a checked state in checkbox column

I am currently integrating ag-grid with a checkbox header component to facilitate selecting/deselecting all rows. However, I am facing an issue where I need to automatically check/uncheck the checkbox column based on a certain field value when fetching d ...

Sending data to <nuxt-link> component without using parameters or passing hidden information to the router without using parameters

Presently, I am utilizing nuxt and vue routing for my web application. In my view, I'm creating my link in the following manner: <nuxt-link :to="'/article/' + article.id"> Afterwards, I extract this article ID on my article page by r ...

Tips for protecting against XSS attacks for APIs accessed by both Angular and non-Angular applications

This query pertains to an application utilizing Angular UI (v8.2.14) calling Spring/Java services. I am grappling with the challenge of safeguarding against XSS vulnerabilities in the most effective manner, but there appears to be conflicting issues at pla ...

Downloading EJS File instead of Displaying on Express.js Router

As I embark on the journey of developing a live video sharing/watching feature using Pure Node.js and without relying on any frameworks, an unexpected issue arose in the middle of the process. The problem occurred when Express started downloading an EJS fi ...

Is it permissible to combine the leaflet plugin *.js and *.css files?

Apologies for the confusion. I am utilizing some leaflet *.js plugins along with supplementary *.css, resulting in numerous additional lines within each of my *.html files' headers. Is it possible to consolidate the *.js and *.css files into one singl ...

I would like my division to split into two halves, each with a width of 50%, and be aligned next to each other using fxLayout

<div fxLayout="row" fxLayoutAlign="space-between" style="background-color: blue;"> <div fxLayout="column" style="width: 50%;">1stOne </div> <div fxLayout="column" styl ...

Remove the container once all of its children have been dismissed

Is it possible to automatically remove the parent container when all of its children elements have been removed? Each child element has a dismissal option that, when clicked, removes the element. I am using backbone.js for this project and would like a so ...

Transforming class attributes in Typescript

I am facing a situation where I need to alter the type of a variable that stores an object based on certain conditions. Here is the variable in question: class MyClass { public referrers: SelectItemGroup[]; } The issue arises when I only need to add a ...

What is the best way to integrate a React component into an Angular project?

Struggling with integrating a React component into an Angular project and unable to make it work. I have a JavaScript file containing the React component that I want to use in Angular. Here's an example: React file... import React from "react"; c ...

What changes can I make to this javascript code?

I am currently utilizing the Google Local Search API along with the Google Maps API. Take a look at it here: After performing a search, the javascript populates both the map and the results adjacent to it. The function responsible for populating the resu ...