JavaScript Reactive: Managing subscriptions in flatMap streams

In my current setup, I have a state$ stream that contains messages$s (an array of message streams). As the State$ is updated, new messages$ are added to the array.

My goal is to have a subscriber handle messages from all messages$ in a single stream, ensuring that only correct events are included.

I attempted to use flatMap to merge the messages$ each time, but encountered an issue where old messages$s (from previous state$ values) were being subscribed multiple times.

How can I resolve this?


  let allMessages$ = state$.flatMap(s => {
      return Observable.merge(s.messages$s)
    }
  )
 allMessages$.subscribe((x)=>{
    console.log('message', x)
    // message from single message$ appear multiple times
  })

The problem arises when the state$ is updated with new items pushed, causing the old ones to be subscribed to multiple times.


state$              --s(1)---------s(2)----
message$s[0].       --m1----m2-----------m4--
message$s[1]        ---------------m3--------
allMessages$        --m1----m2-----m3----m4
                                   m1    m4

s(1) represents the state with one message$, while s(2) signifies the addition of a second message$. As a result, allMessages$ emits messages from item1.

What I am aiming for:


state$              --s(1)---------s(2)-----
message$s[0]        --m1----m2-----------m4--
message$s[1]        ---------------m3--------
allMessages$        --m1----m2-----m3----m4

This simplified situation can be seen in the following fiddle example: http://jsfiddle.net/8jFJH/797/

Answer №1

Considering the simplified scenario you provided, here are the subscription sequences (you can check out the answer here for a better understanding of hot vs. cold observables and subscription flows):

  • Emitting state1
    • Subscribing to typing$
  • Emitting state2
    • Subscribing to typing$
    • Subscribing to typing2$

By using flatMap, there are three subscriptions simultaneously. Using flatMapLatest will result in the following:

  • Emitting state1
    • Subscribing to typing$
  • Emitting state2
    • 'Unsubscribing' from the previous stream emitted in flatMapLatest i.e. Rx.Observable.merge(state.items) i.e. typing$
    • Subscribing to typing$
    • Subscribing to typing2$

Consider replacing flatMap with flatMapLatest and see if that resolves the issue.

Another approach to solving this could involve working with a stream of state changes instead of the entire state (similar to what redux does for react).

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

Error: Unable to locate module: Material-UI - Please check the path and try again

Encountering this error: Error message: Failed to compile ./node_modules/@material-ui/core/Modal/Modal.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'C:\Users\rifat\ ...

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

Sending a parameter to a form within Edge Animate

I'm facing an issue where I need to pass a variable to a form from Edge Animate. Here's the current instruction snippet: sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id="vidn frameborder="0" scrolling="no ...

Using the _id String in a GraphQL query to retrieve information based on the Object ID stored in a

Encountering an issue with my graphql query not returning anything when sending the _id as a string. Interestingly, querying the DB using any other stored key (like name: "Account 1") works perfectly and returns the object. I've defined my Account sch ...

Setting up Stylelint in a Next.js project: A step-by-step guide

I'm looking to incorporate Stylelint into my Next.js app. Can I modify the next.config.js file to include the stylelint-webpack-plugin, in order to receive style errors during compilation? // next.config.js module.exports = { reactStrictMode: true, ...

MERN stack does not have a defined onClick function

I am developing a website for college registration, and I encountered an issue while trying to create a feature that allows students to select a major and view all the associated courses. I made a list of majors with buttons next to them, but whenever I at ...

Encountering issues with jQuery AJAX POST request

I'm currently facing an issue while attempting to send a post request to parse JSON formatted data into my webpage. Here's an example of the query: $("#click").click(function () { $.ajax({ type: "POST", url: "http://ut-pc-236 ...

When implementing afui and jQuery on PhoneGap, an error was encountered: "TypeError: Cannot read property 'touchLayer' of object function (selector, context)"

While working on deploying a web application using phonegap with afui (Intel Appframework UI) for Android, I encountered an issue when testing it in the android emulator. The debug console displayed the following error right after launching the app: Uncau ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

javascript identify dissimilarities within arrays

Working on an Angular 2 application and attempting to identify the difference between two arrays (last seven days and missing dates within the last seven days). Everything works fine when initializing the array through a string, like in example code 1. How ...

Adjust the div's height to 0

I need to dynamically set the height of a div element with a height of 34px to 0px. However, this div does not have a specific class or ID, so I can't use traditional DOM manipulation methods like .getElementById(), .getElementByClassName, or .getElem ...

Is there a clash with another code causing issues in troubleshooting a straightforward jQuery function?

jQuery(document).ready(function() { jQuery("#bfCaptchaEntry").on("click", function(){ jQuery("#bfCaptchaEntry").css("background-color", "#FFFFFF"); }); jQuery("#bfCaptchaEntry").on("blur", function(){ jQuery("#b ...

Leverage the power of Angular's route resolve function

Can anyone assist me with a problem I'm facing? I am looking for a way to delay the display of a view until my data is loaded. After some research, I was thinking of using a resolve in the route, but I can't seem to figure out how to implement it ...

Troubleshooting: Success with AJAX call in Chrome, but issues in IE

Having issues retrieving JSON data from a URL that displays the last 3 numbers of a webpage. The AJAX call functions correctly in Google Chrome but fails in Internet Explorer. I tried disabling caching using cache: false as suggested, but the problem persi ...

What is the process for configuring sendmail in a node.js environment?

After setting up Sendmail on my Nginx server and configuring SMTP for sending emails in my Node.js project, I still encountered issues with emails not being sent. I tried using Sendmail directly, but I'm unsure of how to properly configure it. Here i ...

Jquery-ajax fails to accomplish its task

I am just starting to learn about ajax and recently created a simple page on my local server to practice sending and receiving data from/to a JSON file in the same directory. Although the GET method is working perfectly fine, I am having trouble understan ...

Error during compilation in npm (symbol '_' is not recognized)

After updating all the dependencies in my JavaScript program without making any changes to my components, I encountered an error when running: npm run build The error specifically mentions a problem with one of my components: Failed to compile. ./src/c ...

Modifying Angular 4 instance field in the code does not update the template as expected

One issue I am encountering is that changes in the instance variable in my component class are not automatically reflected in my template file unless I explicitly call ref.detectChanges The method signInWithGoogle in my auth service is called from the com ...