rxjs: observe many targets simultaneously

Imagine you have two distinct subjects s1 and s2 each with their own subscriptions,

const s1 = new Subject<number>();
const s2 = new Subject<number>();

s1.subscribe({
  next: (value) => console.log("s1 emitted", value),
  complete: () => console.log("s1 completed"),
});

s2.subscribe({
  next: (value) => console.log("s2 emitted", value),
  complete: () => console.log("s2 completed"),
});

Now, if we take an observable like of(1), we can pass it through s1 using the following code:

of(1).pipe(tap(s1)).subscribe();

This will result in the output:

s1 emitted 1
s1 completed

However, what if you wanted to process the data through both s1 and s2 simultaneously? One way to achieve this is by:

of(1)
  .pipe(tap((x) => [s1, s2].forEach((s) => of(x).subscribe(s))))
  .subscribe();

which would generate the output:

s1 emitted 1
s1 completed
s2 emitted 1
s2 completed

Is there a more efficient or concise approach for achieving this? I've experimented with merge but without success.

Answer №1

It appears that you are attempting to push data into both s1 and s2 simultaneously. Consider utilizing the pull method instead and defining s1 and s2 as merges from another stream.

const myStream = of(1); // ...

const s1 = new Subject<number>().pipe(
  mergeWith(myStream)
);

const s2 = new Subject<number>().pipe(
  mergeWith(myStream)
);

Simply push data into myStream and it will automatically propagate to both s1 and s2.

Answer №2

One approach could be to devise a utility function that consolidates multiple Observers into a singular entity.

function combineObservers<T>(...observers: Observer<T>[]): Observer<T> {
  return {
    next: (value) => observers.forEach((ob) => ob.next(value)),
    error: (error) => observers.forEach((ob) => ob.error(error)),
    complete: () => observers.forEach((ob) => ob.complete()),
  };
}

const combined = combineObservers(source1, source2);

of(1).pipe(tap(combined)).subscribe()

// source1 emitted 1
// source2 emitted 1
// source1 completed
// source2 completed

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

ReactJS with conditional closing tags

Here is a sample json response : {id: 1, name: a} {id: 2, name: b} {id: 3, name: c} {id: 4, name: d} {id: 5, name: e} {id: 6, name: f} I am looking to organize these by pairs in my React component like so : <div className="group-item"> ...

Encountered difficulties logging in with MongoDB and Node.js

I encountered an issue while attempting to authenticate a user using MongoDB and Node.js. Although no errors are thrown, the system fails to provide the expected data after the user logs in. Below is a breakdown of my code. server.js var port=8888; va ...

Navigating a targeted key-value pair within an array: Step-by-step instructions

Currently, I am dealing with a JSON object that contains over 250 arrays. Each array holds data related to various countries such as population, language, and currency. My objective is to extract a specific key-value pair (country code) from each array and ...

Exploring the Various Path Options in Angular 2 Routing

As a newcomer to Angular and Node JS, I am currently working on an application and struggling with how to efficiently navigate between my different components. Users can input the name of a user and add books associated with them When clicking on a book ...

Dealing with an unexpected token error in JSON when faced with two lines

When downloading content from the server into a file and dealing with multiple lines of JSON, an unexpected token error occurs due to new line characters. How can this issue be resolved? Data from the server {"level":"info","message":"Test Log messages" ...

Performing a search in Select2 only after all remote data has been loaded

The select2 feature is functioning almost as desired. It successfully loads all remote data and formats it correctly when another field is changed. However, I am looking to reintroduce the search function for the retrieved data. Specifically, once the data ...

Issue encountered when compiling a node.js file on Windows 10, resulting in error code 800A03EA

Recently I downloaded and installed Node.js for Windows 10 (x64), accepting all the default settings. C:\WINDOWS\system32>node -v v12.13.0 C:\WINDOWS\system32>npm -v 6.12.0 Next, I decided to test it out by running their "hello ...

What is the recommended method for styling the header of a table generated with the R DT (datatables) package?

Utilizing the datatables JavaScript library, the R package DT creates visually appealing tables. While I am able to customize the cell formatting using the formatStyle() function, I have not come across a method for styling the column headers. Is there any ...

Is the form validation failing to update after an item is removed from the model? Possible bug detected?

Lately, I've been exploring AngularJS and encountered an interesting bug. Let me start by sharing some functional code: View: <body ng-controller="MainCtrl"> <form name="form"> <div ng-repeat="phone in phoneNumbers"> ...

Modify the href value by matching it with the parent div attribute

I am working on an HTML project <div class="1" style="" title="NeedthisText TextIDontneed"> <div class="2> <div class="3"> <a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1"></a> </div> </div> &l ...

Tips for obtaining a specific sorting order based on a wildcard property name

Here's the structure of my JSON object, and I need to sort it based on properties starting with sort_ { "sort_11832": "1", "productsId": [ "11832", "160", "180" ], "sort_160": "0", "sort_180": " ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

text for collecting several responses

I have successfully implemented a post XMLHttpRequest and it is working perfectly. However, I am looking to modify the responseText to receive multiple variables in an array, either comma delimited or any other suitable format. This is how I am currently ...

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Tips for transferring v-model data between components

I am working with a parent form component and a child component, both located in separate files. I am using the Quasar Framework components. How can I pass data from the parent to the child component using v-model? Parent Component <template> < ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

Creating a horizontal slideshow for multiple divs can be achieved through various methods,

I'm feeling a little lost when it comes to creating a slideshow similar to this image: (Symbian^3 music menu) https://i.sstatic.net/oK0F2.png Can anyone provide me with a straightforward code example or a helpful resource to achieve something simila ...

The webpage is inaccessible only on mobile Safari, with an error message indicating a lack of internet

Initially, I do not possess an iPad, however, some clients have reported an unusual issue with one of my websites on the iPad. They are unable to access any page on the website, instead encountering a blank page with the error message: "Safari cannot open ...