Introduction
Hello developers, today we will discuss two important tools in Angular: Subjects and BehaviorSubjects. They are crucial for sharing data smoothly in your app, which is essential for modern web developers.
Web development has grown a lot, and now users expect very interactive and responsive apps. Angular is a helpful tool that lets developers meet these expectations. A big part of this help comes from how Angular handles data using Subjects and BehaviorSubjects.
In the next sections, we will explore Subjects and BehaviorSubjects more, see how they work with examples
Observables
Subjects are fundamental in ensuring seamless data flow across your application. Before diving into Subjects, it’s essential to grasp the basics of Observables and Observers, as Subjects are an extension of these concepts.
Observables are like radio stations, broadcasting data, while Observers are like radio listeners, tuned in to receive this data. In Angular, Observables dispatch data streams, and Observers subscribe to these streams, reacting to any new data emitted.
Subjects
Now, after we have a brief understanding of what observables are, let’s imagine a scenario where you wish to share a single data source among multiple parts of your application. This is where Subjects come into play. Subjects are a special type of Observable that can multicast data to many Observers at once. They ensure that all subscribers share the same data stream, promoting real-time data consistency across your app.
Subjects have two key attributes, multicasting, and their nature as “hot” observables. Let’s talk about each one in detail
Multicasting
Multicasting is a term used to describe a scenario where a single data emission is shared with multiple subscribers. Unlike unicast operations, where each subscriber gets an independent version of the data stream, multicasting ensures that all subscribers share the same data stream. This is especially useful when you have multiple parts of your application that need to react to or process the same data in real time.
In the context of Subjects within Angular, multicasting is a native capability. When a Subject emits a new data value, this value is sent to all subscribers simultaneously. This shared nature of data emission facilitates real-time data consistency across various parts of your application, ensuring that every subscriber receives and processes the same data.
Let’s take the following example
import { Subject } from 'rxjs';
// Create a new Subject
const mySubject = new Subject<number>();
// Subscribe two observers to the Subject
mySubject.subscribe(value => {
console.log(`Observer 1 received: ${value}`);
});
mySubject.subscribe(value => {
console.log(`Observer 2 received: ${value}`);
});
// Emit values through the Subject
mySubject.next(10);
mySubject.next(20);
You should see the following output
In this example, we create a Subject mySubject
. We then subscribe two observers to mySubject
. When we emit values using mySubject.next(value)
, both observers receive the emitted values simultaneously. This showcases the multicasting nature of Subjects.
“Hot” Observables
The concept of “hot” and “cold” observables is foundational in understanding how data streams behave in reactive programming.
- Cold Observables: A cold observable starts emitting data only when it has a subscriber. Each subscriber gets its own independent execution of the observable, meaning the data stream is started afresh for each subscriber.
- Hot Observables: On the contrary, hot observables begin emitting data as soon as they are created, irrespective of whether or not they have subscribers. The data is emitted in real-time, and any subscriber that hooks into a hot observable receives data from the point of subscription onwards. They do not get the data that was emitted before they subscribed. Let’s demonstrate both, the hot and cold observables in practical examples respectively
// Hot observable example
import { Subject } from 'rxjs';
// Create a new Subject
const mySubject = new Subject<number>();
// Emit a value before any observer has subscribed
mySubject.next(10);
// Subscribe an observer to the Subject
mySubject.subscribe(value => {
console.log(`Received: ${value}`);
});
// Emit another value
mySubject.next(20);
You should see this output: Received: 20
In this example, even though a value is emitted before any observer has subscribed, the observer only receives the value emitted after it subscribed, not the value emitted before. This behavior is typical of hot observables. They are active even before subscription and the data is emitted in real-time, but subscribers only get the data from the point they subscribed onwards.
// Cold observable example
import { Observable } from 'rxjs';
// Create a cold observable
const coldObservable = new Observable<number>(observer => {
console.log('Observable execution');
observer.next(Math.random());
});
// Subscribe observer 1 to the cold observable
coldObservable.subscribe(value => {
console.log(`Observer 1 received: ${value} (random number)`);
});
// Subscribe observer 2 to the cold observable
coldObservable.subscribe(value => {
console.log(`Observer 2 received: ${value} (random number)`);
});
You should see this output
In this example, we create a cold observable coldObservable
that emits a random number when an observer subscribes to it. We then subscribe two separate observers to coldObservable
.
The output shows that each observer triggers the observable’s execution separately, and each observer receives a different random number. This is characteristic of cold observables, where each subscriber triggers a new execution of the observable and receives a unique set of emitted values.
This behavior contrasts with hot observables (like Subjects), where all observers share the same execution of the observable and receive the same values.
To summarize, Subjects are categorized as hot observables because they start emitting data right away upon creation. This characteristic of Subjects ensures that data is emitted in real-time, making them a suitable choice for scenarios that demand real-time data handling, such as live updates or real-time monitoring systems.
BehaviorSubjects
BehaviorSubject is a special kind of Subject, it comes with the unique feature of holding onto the most recent value. This feature is powerful that helps in managing the state of your application effectively.
When we create a BehaviorSubject, we start with an initial value. Unlike Subjects, BehaviorSubjects remember the last value they held, which is very useful.
BehaviorSubjects are good at holding onto a value and sharing it across different parts of a website. When the value changes, BehaviorSubjects ensures every part of the website knows about the new value.
Here’s a simple example to show how BehaviorSubjects work:
import { BehaviorSubject } from 'rxjs';
// Create a BehaviorSubject with a starting value of 0
const behaviorSubject = new BehaviorSubject<number>(0);
// A part of the website subscribes to the BehaviorSubject
behaviorSubject.subscribe(value => {
console.log(`Part 1 received: ${value}`);
});
// Change the value to 1
behaviorSubject.next(1);
// Another part of the website subscribes
behaviorSubject.subscribe(value => {
console.log(`Part 2 received: ${value}`);
});
// Change the value to 2
behaviorSubject.next(2);
You should see this output
Let’s break it down
- We create a BehaviorSubject with a starting value of 0.
- Part 1 of the website subscribes to the BehaviorSubject and knows the value is 0.
- When we change the value to 1, Part 1 knows about it.
- When Part 2 of the website subscribes, it immediately knows the value is 1, not 0.
- When we change the value to 2, both parts know about it.
This shows how BehaviorSubjects share values across different parts of a website.
Comparing Subjects and BehaviorSubjects
In Angular, Subjects and BehaviorSubjects are tools that help us manage and share data in our apps. Although they seem similar, they have some differences. Let’s talk about these differences in a simple way and see when to use which tool.
- Subjects: Ideal for scenarios where multicasting is required but there’s no need for an initial value or to remember the last emitted value. Subjects are simpler and are a great fit for handling events or multicast notifications.
- BehaviorSubjects: Perfect for state management purposes where the initial state is important, or whenever you need to ensure new subscribers receive the last emitted value. They are invaluable when parts of your app need to stay updated with the current value.
Conclusion
In conclusion, we learned about two helpful tools in Angular: Subjects and BehaviorSubjects.
- Subjects: They help share data quickly with many parts of your app at once.
- BehaviorSubjects: They do the same, but also remember the last value shared, which is helpful in many situations.
These tools are very useful in making sure your app works smoothly and keeps data organized. There’s a lot you can do with Subjects and BehaviorSubjects in Angular, and using them can make handling data in your app much easier. Happy coding!
👉 Visit my personal blog 👈
Top comments (0)