Understanding rxjs Subjects
Rxjs is great. It helps you with composing and subscribing to data streams. You probably do this a lot with “plain” Observables. Rxjs however offers a multiple classes to use with data streams, and one of them is a Subject.
If you think you understand Observables, read on! Else i suggest you to read more about it in my other article: Understanding, creating and subscribing to observables in Angular.
Subjects
A Subject is like an Observable. It can be subscribed to, just like you normally would with Observables. It also has methods like next()
, error()
and complete()
just like the observer you normally pass to your Observable creation function.
The main reason to use Subjects is to multicast. An Observable by default is unicast. Unicasting means that each subscribed observer owns an independent execution of the Observable. To demonstrate this:
While Observables are unicast by design, this can be pretty annoying if you expect that each subscriber receives the same values. Subjects can help us overcome this issue. As mentioned…