Understanding Observables and Subjects in RxJS. Multicasting values

Eugen Sadouski
Eugen Sadouski

Full stack developer

July 26, 2018

Understanding Observables and Subjects in RxJS. Multicasting values

Hello guys!

When I just started working with Angular 2+ I faced quite tricky and kinda complicated issue to me. I’ve noticed many people got into the same situation quite often. So I will try to explain what Subject and Observable in RxJS mean and what is the main difference between these two terms.

Pattern Observer

One of the first thing that you will read about RxJS is Observer pattern. This is important and fundamental pattern used in RxJS. In a standard form of the pattern there are two basic terms - Subject & Observer. But RxJS treats this pattern a bit differently, sometimes confusing for you. So let’s not focus on it and take a look at the simplified version.

pattern observer

There are two central terms. The first one is called Observer and you might think of it as of someone who receives data. But before it starts to obtain data, it’s necessary to subscribe it to Observable. This is the second term from the global concept and you can think of it as of someone who sends data. I like the example with Excel cells - a cell notifies every dependent formula and asks to re-calculate. You can read more here

As you can see it’s quite a simple concept and that’s all we need to understand from the Observer pattern.

Observable

You may ask where is the Subject on the previous picture, but before I answer, it’s necessary to understand what Observable does under the hood. The main aspect you should understand is that Observable is just a function that relates Observer and Data Producer. Here is the code example for better understanding:

In this example you can see emitValue function puts Observer inside and every second emits increased value by calling next method from Observer object. Pay attention that emitValue returns function that will clear interval and stop emitting process.
The next function is createObservable. It returns an object with subscribe property, referring to which emitValue function will be invoked.

There is simple Observer, which will output the value in a console. The most interesting part follows. We’ve created new Observable by calling createObservable and passing function. Now it’s just an object with subscribe property and emitValue function inside. Then we call subscribe and it gives us unsubscribe (clearInterval) method.
So after running this example, you will see 0…1…2…3 in your console. I’ve prepared a working example. It’s available here

To sum up, what you really need to understand:

  1. Under the hood Observable is just a function
  2. To start receiving data, you need to call subscribe
  3. To stop receiving – call unsubscribe

There is an awesome article by Ben Lesh about Observables, where you can read more about Observable concept.

Problem with Observable

As you have already read from the previous chapter, when you call subscribe it invokes a function, which will produce data. It means that if you call subscribe, it calls Producer function once again. Speaking in terms of RxJS, if we subscribe new Observer to already existing Observable, it will receive the same data as the first Observer. Let's see the Marble diagram.

marble diagram
  • What if we just want to see the counter in a state that already exists but need to subscribe new Observer not invoking Data producer once again.
  • What if we want to share one data with many Observers.

The answer to these questions is Hybrid. Let's see what it means.

Hybrid

Hybrid is an object that can be both Observable and Observer at the same time. We can subscribe it to Observable as well as subscribe Observer to this Hybrid.

Observer to Hybrid

What benefit we can get from it? While using Hybrid we can solve the problem of sharing the same data with many Observers. In that way marble diagramm would be as follows:

observers

Scroll down to see a simple example of how this Hybrid can work under the hood.

Here is Hybrid object with internal list of Observers, subscribe and next methods. When we call subscribe method it will push new Observers to the list. And when data producer emits new value, it calls next method in Hybrid, that will iterate over all Observers and notify each of them. So in this way we can be sure that each Observer has been notified.
Here we are, really close to understanding such a term as Subject.

Subject and its types

So what is Subject? The answer is obvious. Subject is Hybrid between Observable and Observer, it is really similar to the one we have discussed in the previous chapter.
Now as we already know what Subject is and how it works, let's see other types of Subject available in RxJS.

  • BehaviorSubject

The difference from Subject is that it keeps the last received data and can give it to us by request. As it stores value, it’s necessary to put the default data during the init process.

  • Replay Subject

Replay Subject is pretty similar to the previous one. It also stores value, but the difference is that it can store not only the latest value, it stores as many values as we set via bufferSize or windowTime parameter.

  • Assync Subject

This type of Subject is used for sending only the last value to the Observers, before the onCompleted notification or onError execution.

What you really should know is that Subject has both features of Observer and Observable; using it gives us a possibility to share one execution between many Observers.

Multicast

Returning back to the problem of sharing one data between many Observers, let me introduce you multicast.
For sharing data with many Observers, first we should create Subject, then subscribe Observers to it and then subscribe Subject to Observable, as in the picture below.

multicast is an operator and it makes sharing process easier for us. Let's see an example of using it:

It’s pretty similar with the previous example, but instead of creating Subjects every single time, it’s possible to pass it inside multicast operator. After multicast invoked, it returns ConnectableObservable. It’s pretty similar to the ordinary Observable, except one thing - operator connect. This operator will subscribe inner Subject to the data source by demand. It means that we can control time of emitting data.
Using multicast give us an opportunity to write code in chainable style and prevents us from boilerplate code.

Publish

Another useful operator that makes our lives easier is publish.
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/publish.ts
As you can see from the source code it’s just a wrapper around multicast. It creates Subject and passes it to the multicast operator. There is one interesting thing called Selector function used as a sandbox. It’s quite a tricky thing and deserves its own blog post to be written. So let's skip it for now.
As you have seen from the source code, publish operator creates Subject inside.
What if we need different types of Subject? For this purpose there are three more types of publish operator:

  • PublishBehavior uses BehaviorSubject
  • PublishReplay uses ReplySubject
  • PublishLast uses AsyncSubject

In addition publish operator returns ConnectableObservable. Moreover we need to remember: it’s necessary to call unsubscribe for all listeners to avoid memory leaks. We unsubscribe not only observers but also ConnectableObserver, which we unsubscribe from the source, too.

const sub = observable.connect();  
   const subA = observable.subscribe(observerA);
   const subB = observable.subscribe(observerB);

   subA.unsubscribe();
   subB.unsubscribe();
   sub.unsubscribe();

Creators of RxJS have taken care of us and implemented refCount operator.

RefCount

As you might have guessed refCount helps us to manage subscription. It does subscribe and unsubscribe Observers automatically.

When new Observer is subscribed, links of active Observers will be increased and refCount will automatically make a subscription. From the other hand when Observer is unsubscribed, links of active Observers will be decreased. When the number reaches 0, RefCount triggers unsubscription from the source.
So with using this operator we don’t need to remember about subscription and unsubscription, it will be called automatically, what in turn will save us from the memory leak.

Share

The share operator is a wrapper for the refCount, but having some difference. If we use refCount after onCompleted notification, then all Observers will be unsubscribed, number of active links will be decreased up to null and it will automatically unsubscribe ConnectableObservable from the source. After that, if we decide to subscribe new Observer, it will receive only complete notification.

Another behavior with using share operator. In comparison to RefCount, share uses subject factory inside. Subject factory is a simple function that creates and returns new Subject every time you call it. That means that if we decide to subscribe to new Observable after the onComplete has happened, it will create new Subject and subscribe it to the source. So we will be able to receive data once again and not seeing Complete event every time.

That’s it. I’ve tried to explain the most important and confusing things in RxJS, from my point of view. However there are still some tricky things left. So leave comments and questions and we will try to figure it out next time for you.

Thank you for reading!

Contact us
Akveo's case

Retool Dashboards with HubSpot Integration

Our client needed a centralized tool to aggregate account and contact activity, improving visibility and decision-making for the sales team.

The solution
We built a Retool application integrated with HubSpot, QuickMail, and Clay.com. The app features dashboards for sorting, filtering, and detailed views of companies, contacts, and deals, along with real-time notifications and bidirectional data syncing.

The result

  • MVP in 50 hours: Delivered a functional application in just 50 hours.
  • Smarter decisions: Enabled data-driven insights for strategic planning.
  • Streamlined operations: Reduced manual tasks with automation and real-time updates.

Learn more about the case

See More
See Less
Akveo's case

Lead Generation Tool to Reduce Manual Work

Our client, Afore Capital, a venture capital firm focused on pre-seed investments, aimed to automate their lead generation processes but struggled with existing out-of-the-box solutions. To tackle this challenge, they sought assistance from our team of Akveo Retool experts.‍

The scope of work
The client needed a tailored solution to log and track inbound deals effectively. They required an application that could facilitate the addition, viewing, and editing of company and founder information, ensuring data integrity and preventing duplicates. Additionally, Afore Capital aimed to integrate external tools like PhantomBuster and LinkedIn to streamline data collection.

The result
By developing a custom Retool application, we streamlined the lead generation process, significantly reducing manual data entry. The application enabled employees to manage inbound deals efficiently while automated workflows for email parsing, notifications, and dynamic reporting enhanced operational efficiency. This allowed Afore Capital's team to focus more on building relationships with potential founders rather than on administrative tasks.

Learn more about the case

See More
See Less
Akveo's case

Retool CMS Application for EdTech Startup

Our client, CutTime, a leading fine arts education management platform, needed a scalable CMS application to improve vendor product management and user experience.

The scope of work
We developed a Retool application that allows vendors to easily upload and manage product listings, handle inventory, and set shipping options. The challenge was to integrate the app with the client’s system, enabling smooth authentication and product management for program directors.

The result
Our solution streamlined product management, reducing manual work for vendors, and significantly improving operational efficiency.

Learn more about the case

See More
See Less
Akveo's case

Building Reconciliation Tool for e-commerce company

Our client was in need of streamlining and simplifying its monthly accounting reconciliation process – preferably automatically. But with a lack of time and low budget for a custom build, development of a comprehensive software wasn’t in the picture. After going through the case and customer’s needs, we decided to implement Retool. And that was the right choice.

The scope of work

Our team developed a custom reconciliation tool designed specifically for the needs of high-volume transaction environments. It automated the processes and provided a comprehensive dashboard for monitoring discrepancies and anomalies in real-time.

The implementation of Retool significantly reduced manual effort, as well as fostered a more efficient and time-saving reconciliation process.

→ Learn more about the case

See More
See Less
Akveo's case

Creating Retool Mobile App for a Wine Seller

A leading spirits and wine seller in Europe required the development of an internal mobile app for private client managers and administrators. The project was supposed to be done in 1,5 months. Considering urgency and the scope of work, our developers decided to use Retool for swift and effective development.

The scope of work

Our developers built a mobile application tailored to the needs of the company's sales force: with a comprehensive overview of client interactions, facilitated order processing, and enabled access to sales history and performance metrics. It was user-friendly, with real-time updates, seamlessly integrated with existing customer databases. 

The result? Increase in productivity of the sales team and improved decision-making process. But most importantly, positive feedback from the customers themselves.

→ Learn more about the case

See More
See Less
Akveo's case

Developing PoC with Low Code for a Tour Operator

To efficiently gather, centralize, and manage data is a challenge for any tour operator. Our client was not an exception. The company was seeking to get an internal software that will source information from third-party APIs and automate the travel itinerary creation process. Preferably, cost- and user-friendly tool.

The scope of work

Our experts ensured the client that all the requirements could be covered by Retool. And just in 40 hours a new software was launched. The tool had a flexible and easy-to-use interface with user authentication and an access management system panel – all the company needed. At the end, Retool was considered the main tool to replace the existing system.

→ Learn more about the case

See More
See Less
Akveo's case

Testing New Generation of Lead Management Tool with Retool

Our client, a venture fund, had challenges with managing lead generation and client acquisition. As the company grew, it aimed to attract more clients and scale faster, as well as automate the processes to save time, improve efficiency and minimize human error. The idea was to craft an internal lead generation tool that will cover all the needs. We’ve agreed that Retool will be a perfect tool for this.

The scope of work

The project initially began as a proof of concept, but soon enough, with each new feature delivered, the company experienced increased engagement and value. 

We developed a web tool that integrates seamlessly with Phantombuster for data extraction and LinkedIn for social outreach. Now, the company has a platform that elevates the efficiency of their lead generation activities and provides deep insights into potential client bases.

→ Learn more about the case

See More
See Less
Akveo's case

Building an Advanced Admin Portal for Streamlined Operations

Confronted with the need for more sophisticated internal tools, an owner of IP Licensing marketplace turned to Retool to utilize its administrative functions. The primary goal was to construct an advanced admin portal that could support complex, multi-layered processes efficiently.

The scope of work

Our client needed help with updating filters and tables for its internal platform. In just 30 hours we've been able to update and create about 6 pages. Following features were introduced: add complex filtering and search, delete records, styling application with custom CSS. 

Together, we have increased performance on most heavy pages and fixed circular dependency issues.

→ Learn more about the case

See More
See Less
Akveo's case

Creating MVP Dashboard for Google Cloud Users

Facing the challenge of unoptimized cloud resource management, a technology firm working with Google Cloud users was looking for a solution to make its operations more efficient. The main idea of the project was to create an MVP for e-commerce shops to test some client hypotheses. Traditional cloud management tools fell short.

The scope of work

Determined to break through limitations, our team of developers turned Retool. We decided to craft an MVP Dashboard specifically for Google Cloud users. This wasn't just about bringing data into view; but about reshaping how teams interact with their cloud environment.

We designed a dashboard that turned complex cloud data into a clear, strategic asset  thanks to comprehensive analytics, tailored metrics, and an intuitive interface, that Retool provides. As the results, an increase in operational efficiency, significant improvement in cost management and resource optimization.

→ Learn more about the case

See More
See Less
Akveo's case

Elevating CRM with Custom HubSpot Sales Dashboard

Our other client, a SaaS startup, that offers collaborative tools for design and engineering teams, was on a quest to supercharge their sales efforts. Traditional CRM systems were limited and not customizable enough. The company sought a solution that could tailor HubSpot to their workflow and analytics needs.

The scope of work

Charged with the task of going beyond standard CRM functions, our team turned to Retool. We wanted to redefine how sales teams interact with their CRM. 

By integrating advanced analytics, custom metrics, and a user-friendly interface, our developers provided a solution that transformed data into a strategic asset.

In 40 hours, three informative dashboards were developed, containing the most sensitive data related to sales activities. These dashboards enable our customer to analyze sales and lead generation performance from a different perspective and establish the appropriate KPIs.

→ Learn more about the case

See More
See Less
Akveo's case

Retool for Sales and CRM Integration

See More
See Less
Akveo's case

Building a PDF Editor with Low-Code

Our client, a leading digital credential IT startup, needed a lot of internal processes to be optimized. But the experience with low-code tools wasn’t sufficient. That’s why the company decided to hire professionals. And our team of developers joined the project.

The scope of work

The client has a program that designs and prints custom badges for customers. The badges need to be “mail-merged” with a person’s info and turned into a PDF to print. But what is the best way to do it?

Our developers decided to use Retool as a core tool. Using custom components and JavaScript, we developed a program that reduced employees' time for designing, putting the data, verifying, and printing PDF badges in one application.

As a result, the new approach significantly reduces the time required by the internal team to organize all the necessary staff for the conference, including badge creation.

→ Learn more about the case

See More
See Less
Subscription
Subscribe via Email

Want to know which websites saw the most traffic growth in your industry? Not sure why your SEO strategy doesn’t work?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

By clicking “Subscribe” you agree to Akveo Privacy Policy and consent to Akveo using your contact data for newsletter purposes

More articles by themes

Cross
Contact us
AnnaRodionEvgenyExpertExpertExpert
Cross
Got any questions?
Our domain expert is here to answer
If you have any questions, feel free to leave me a personal message on LinkedIn. We are here to help.
Thanks for your question
We will contact you soon
We have a problem
Please, check the entered data
Got any questions?