Implementing RXJS subscription using a Subject object

What is the benefit of using "Subscribe providing subject" and what does this entail: 1- The purpose of using subscribe providing subject

import { Subject, from } from 'rxjs';
 
const newSubject = new Subject<number>();
 
newSubject.subscribe({
  next: (value) => console.log(`observerA: ${value}`)
});
newSubject.subscribe({
  next: (value) => console.log(`observerB: ${value}`)
});
 
const newObservable = from([1, 2, 3]);
 
newObservable.subscribe(newSubject); // You can subscribe by providing a Subject
 
// Output:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2
// observerA: 3
// observerB: 3

Answer №1

When you subscribe to an RxJS Observable, you do so with the help of an Observer. Below is the TypeScript definition for an observer.

interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

You can also use a partial observer (implementing only certain callbacks) or even just a function (similar to a partial observer with just the next callback).

An interesting fact is that a Subject actually implements the Observer interface, making it usable as an observer itself! This provides a straightforward way to multicast an observable (and ties into how multicasting operators function to some extent).

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 encountered while fetching files from Google Cloud bucket using Firebase functions: RangeError - Maximum call stack size exceeded

I'm currently trying to access Firestore backup files stored in a Google Cloud bucket: export const retrieveFirestoreBackup = functions.https.onCall( async (data: RetrieveFirestoreBackupPayload, context) => { try { return await sto ...

Undefined elements in an array of objects in Javascript

I've been working on creating an array of objects in JavaScript, but I'm facing an issue when attempting to print the array to the console in Chrome. It keeps returning undefined unless I print the array right after pushing new elements into it. ...

The issue with AngularJS 2-way-binding failing to refresh

Recently, I experimented with angularJS in conjunction with a range-slider-directive that can be found here: https://github.com/supertorio/angular-rangeslider-directive Initially, everything worked well while using the data-model solely within my HTML pa ...

Issue with jqGrid Multiple Selection

When constructing my jqgrid, I utilize the following code: multiselect: true This enables a check all column. However, clicking the check all checkbox (located at the header) selects all checkboxes, but does not click the checkboxes in each row. You can ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

Creating a static Top Bar that remains unaffected by page refreshing using Ajax or any other method can be achieved by implementing JavaScript and CSS

I've designed a sleek top bar for my upcoming website project. Below is the CSS code snippet for creating this clean div bar: .topbar { display:block; width:100%; height:40px; background-color:#f5f5f5; } I'm looking to incorporate a simple .SWF ...

Why isn't my code able to locate the navigation partial?

Here is my contact.ejs file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Title</title> <style> body { background: skyblue; font-family: verdana ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

How can I troubleshoot the issue of not receiving a response while attempting to upload an image using Postman with my Cloudinary-Express API?

Currently developing a backend nodejs/express API to upload image files to Cloudinary, encountering an error during testing with Postman. Below is the backend code: app.post( '/api/upload/:id', asyncHandler(async (req, res) => { try { ...

Encountering an issue with React NextJS when attempting to upload a file and submit form data simultaneously through the NextJS API. The error message received is "501 Not

I am currently working on a Next.js application that includes a form where users can upload a file while providing their personal information. I have encountered an issue with Multer and the next-connect middleware, specifically when setting bodyParser to ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

Troubleshooting: Issue with Updating Prototype Ajax Function

I am currently utilizing Prototype within the pylons framework and attempting to execute an Ajax call. Below is the structure of my html: <form method="POST" action = "javascript:void(0)" onsubmit = "new Ajax.Updater('graph','/saffron_m ...

The code is malfunctioning on this site (yet functions perfectly on a different website)

So I have a question that may seem silly, but it's worth asking. I'm attempting to create a sticky div element that stays in place when you scroll past a certain point on the page. This is the script I have: <script type="text/javascript"> ...

Developing a downloadable PDF version of an online platform

For weeks now, I have been tirelessly searching for a solution to a problem that has stumped me once before. The Challenge: My company created a sophisticated web-based data analytics suite for a major beverage distributor. Our client is now requesting a ...

Is there a gentle approach to transferring calendar event variables in JavaScript?

The example provided below showcases a @model that contains data. To utilize specific portions of the data, I have transformed it into a Json object using Json.Serialize. This was necessary because the events:[ ] section requires data in a particular form ...

Deactivate the Submit button when the database field has been populated

My form includes a submit button. The Submit button should be disabled if the "price" for a specific product is already filled: PHP Code <?php $host="localhost"; $username="root"; $password=""; $db_name="ge"; $con=mysqli_connect("$h ...

Utilize JavaScript, MySQL, and PHP to input data into a database

My JS function is supposed to make an ajax request, but for some reason it's not working. I've checked the URL in an alert and all variables are declared. var request = new XMLHttpRequest(); var url = "ajax_js/q_ajax.php?q="+ques+ ...

Nodemailer is functioning properly in a local environment, however, it is encountering issues when

I am facing an issue with Nodemailer where it is sending emails successfully on my local machine but not on Lambda. I have tried various solutions from Stack Overflow, but none of them seem to be working for me. One suggestion was to make the sendEmail fun ...

NodeJs:- Retrieve data from the initial dropdown menu and display it dynamically in the secondary dropdown

Currently, I am working on a dropdown list and facing an issue where the results displayed in the second dropdown need to be filtered based on the selection made in the first dropdown. The EJS code snippet that I am using is: <div class="form-group"& ...

Struggling with implementing Bootstrap modal JavaScript in Rails 4, nothing seems to work!

This situation has been addressed in numerous posts, but despite my efforts to find a solution among them, I have yet to come across one that works for me. I am faced with the task of opening a modal that requires JavaScript modifications before being dis ...