The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner:

this.wsObserver = Observable.create(observer=>{
          this.websocket.onmessage = (evt) => {
              console.info("ws.onmessage: " + evt);
              observer.next(evt);
          };
      });

While this method seems to work fine, when I subscribe multiple times, only the last subscriber triggers:

this.wsObserver.subscribe((result) => {
        console.info("! result: " + result);
      });
      this.wsObserver.subscribe((result) => {
        console.info("!2 result: " + result);
      });

It seems that only !2 result: is being logged. Can anyone explain why this is happening and what mistake might I be making?

Answer №1

The issue arises from the fact that you are constantly overwriting the onmessage handler in your creation process, resulting in only the last subscriber being triggered (as they set the final value of onmessage).

To resolve this, consider the following approach:

let messageSubject = new Subject();
this.websocket.onmessage = (evt => messageSubject.next(evt));

Then, you can use:

messageSubject.subscribe(...) 

This will allow for multiple subscribers to work simultaneously without any issues.

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

Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further. This div will be located on the right-hand side of my page, clo ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Issue: friends.js file contains an unexpected token "<" error after implementing express.static and modifying HTML content upon button click

On localhost:9000, I'm attempting to load home.html initially. However, when I try it with my current code, I encounter the error: friends.js:1 Uncaught SyntaxError: Unexpected token <. I'm unsure about the meaning of this error. Additionally, ...

Error in Express JS: Attempting to access properties of an undefined variable (reading '0'). Issue with SQL query

Struggling to insert something in my database and then access it directly after. Due to the asynchronous nature of node.js, my plan doesn't seem to work out. However, I am confident that there is a solution to make this happen. Here's the code sn ...

Retrieve the value with `eventArgs.get_value()` function to obtain the selected text instead of the ID

When I populate a textbox with autocomplete using the code below, it only returns the selected text and not the rowid. Any idea why alert(eventArgs.get_value()) doesn't return the actual ID of the row in SQL? <script language="javascript" type="te ...

The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8 I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide. Data Object Structure data: functio ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

Switch out the words within the input box

My code has the ability to convert words to numbers, however, when I try to paste a text like: three four one one four five six one, the output I receive is: 3411456one If I click on the text input again, the word 'one' changes to '1', ...

What is the best approach for converting a string containing data into a format suitable for displaying in a series on React

Here's a question that may seem simple, but is a bit of a challenge to explain if you're not familiar with highcharts. Imagine you have a simple block of code like this: ` [{"name":"Name1","data":[{"x":1477621800,"y":114,"name":"Name2"}]` and y ...

Using AngularJS to apply filters to JSON data

I'm having trouble filtering a JSON array. Here's an example of what my JSON array looks like: vm.users = [{ "fname": "Antoan", "lname": "Jonson", "Address": "Address1" }, ... ] How do I filter by last name starting with a specific term (e.g. & ...

Is it possible to incorporate knockout.js within a Node.js environment by utilizing .fn extensions in custom modules?

I'm currently exploring the possibility of implementing the knockout.mapping.merge library in node.js, but I seem to be facing a challenge when it comes to extending ko objects within the module's scope. I am struggling to figure out how to exten ...

Blocking negative values when a button is clicked in Vue.js using v-on:click

How can I prevent the counter from going below 0 when clicked in this Vue component? Do I need to create a separate method to block it? Thank you for your assistance. <button v-on:click="counter.document -= 1">-</button> <h3>{{coun ...

Tips for accessing data from a local JSON file in your React JS + Typescript application

I'm currently attempting to read a local JSON file within a ReactJS + Typescript office add-in app. To achieve this, I created a typings.d.ts file in the src directory with the following content. declare module "*.json" { const value: any; ex ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

Leveraging the withWidth higher order component (HOC) provided by

I am currently using version 3.9.2 of Material UI and experimenting with the withWidth HOC in a server-side rendered application. When I disable Javascript in the debugger options of Chrome Developer Tools, everything functions as expected by displaying t ...

Unable to retrieve elements from the eBay website using JavaScript within a Chrome extension

I recently developed a Chrome extension that scrapes all orders from an eBay orders page. It was working flawlessly last month, but suddenly I am facing issues accessing some elements. Here is the snippet of code causing trouble: let elGridComp = document ...

Combining two arrays of names and values into a fresh object using Javascript

Trying to merge two arrays, one for column headers: cNames = ["Year","Count"] And another for data: mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143] The goal is to combine them like this: [ { Year: "2005", Count: 5021 ...

Fetching response headers object in redux using React.js

Currently, I am using Redux in React.js to fetch the most starred repositories from the past 30 days. However, I now want to implement pagination using the headers provided by the GitHub API. How can I modify my code to extract the headers from the respons ...

Clicking on links will open them in a separate tab, ensuring that only the new tab

Is there a way to open a new tab or popup window, and have it update the existing tab or window whenever the original source link is clicked again? The current behavior of continuously opening new tabs isn't what I was hoping for. ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> S ...