Introduction
Hello readers. In this blog, we will be understanding the difference between unicast and multicast observables. Before getting started, let us understand what is observable.
An observable is a function that can convert an ordinary stream of data into an observable stream of data i.e it can deliver multiple values of any type. Observables are considered declarative which means they will not execute until there is a subscriber which can receive those emitted values. You can subscribe to an observable using the subscribe() function.
There is another term that is observer which you should be aware of before moving further.
The observer is the one which will subscribe to the observables and receive the emitted values.
So, in easier terms observable is your data source, subscribe is a function, and observer is the one receiving values.
Now, that we are aware of all these terms, let’s dive into the unicast and multicast scenario.
Unicast Observables
Unicast is an observable whose emitted values are not shared amongst the subscribers. All the subscribers subscribing to that observable will receive different values.
Multicast Observables
Multicast is another type whose emitted values are shared amongst all subscribers. That means all the subscribers subscribing to it will receive the same values.
Let us understand it better with the help of an example:
const observable = new Observable(obj =>
obj.next(Math.floor(Math.random() * 10)+1));
observable.subscribe(data => {
console.log("First Subscription value: ",data);
});
observable.subscribe(data => {
console.log("Second Subscription value: ",data);
});
Here we have created an observable which will emit random values between 1 to 10. We have made two subscriptions to this observable. Now when we run this. This is the output
First Subscription value: 8
Second Subscription value: 3
Now let us change the above code slightly and use subjects.
Subjects are special kinds of observables that can act both as an observable and an observer.
const subject = new Subject();
subject.subscribe(data => {
console.log("First Subscription value: ",data);
});
subject.subscribe(data => {
console.log("Second Subscription value: ",data);
});
subject.next(Math.floor(Math.random() * 10)+1);
This time we created a subject and emitted the same random number between 1 to 10. But this time the output will be different. Here is the output that we get in the console:
First Subscription value: 3
Second Subscription value: 3
So, this is the main difference between unicast and multicast. By default, observables are unicast and subjects are multicast.
Conclusion
Working with observables is very common in Angular so we must be aware of the difference between unicast and multicast observables. Here we learned the difference between them with the help of an example.
For more updates on such topics, please follow our LinkedIn page- FrontEnd Studio.