RxJS Crash Course – Subject and Multicast Example

0

We just have one more topic to cover and that’s the RxJS Subject. A subject is just an observable with a few extra bonus features.

It has the ability to emit new data to its subscribers by acting as a proxy to some other data source.

This will make more sense after the next couple of samples.

Subject in RxJS

So, here we have a plain observable and we’re going to convert it to a subject when we subscribe to it. It emits the values just like a normal observable would. But the real benefit of the subject is to be able to call next on it.

So what we do is create a new subject and then we’ll create a couple of subscriptions to it. And then we can just call subject next with some value that’s not something you can do on a normal observable. Then we’ll set another next call inside of a timeout.

So, the main benefit of a subject is being able to broadcast new values to subscribers without having to rely on some source data.

Multicast in RxJS

On this topic, we’re gonna look at one last thing and that’s multicast. It’s used to send values to multiple subscribers. But not any related side effects so we create a data source that is the click events happening in the DOM.

And then we use the do operator to print do one time. This is an example of a side effect. Imagine we had a hundred subscribers it would run this code for every single one a bomb.

So if you had a hundred clicks and a hundred subscribers this code would run 10,000 times.

Well, we actually want is for it to only run on the 100 clicks coming from the source observable we can do this by calling multicast on the original observable and have it return a new subject.

Then we can add a couple of subscriptions to the subject then lastly we need to call connect on that subject. When we start clicking in the Dom. We’ll see that we get the values sent to the subscribers and the side effect only runs once even though.

There are multiple subscribers this could be highly beneficial if you have multiple subscribers to a single data source that is running some sort of side effect.

That’s it for my RxJS QuickStart if this article series helped you please share it with your friends.

 

0