What are they, after all? When to use what!
I have been using Subjects in reactive programming. But, I have always faced difficulty in understanding when to use what type of subject. In this article I’d be going through the types of subjects.
What is an Observable?
In a nutshell, Observable is a function which returns a stream of values to an observer over time. Observer reacts to whatever values an Observable emits. It implements the Observer Design Pattern.
Observer Design Pattern: A publisher publishes data and the consumer
subscribes to the publisher to receive the data and
unsubscribes to stop receiving that data. Publisher doesn’t know who you are and how you are subscribing, it just delivers the value to you because you are a subscriber (loose coupling).
What is an Observer?
An Observer is the consumer of the values emitted by the Observable. It is an object with 3 callback methods
error(e). Observable will call Observer’s
next(value)method to emit data.
What is a Subject?
Subjects are a special kind of Observables. They can be Observables and Observers both. If we’re using Subject as Observable, then to emit values we can use
next(value). Subjects are similar to EventEmitters; they just emit the same data to all its subscribers and maintain a registry of many listeners.
Basic usage of a Subject is to get the value from the publisher and give it to all of its consumers.
Here, we created a Subject and attached two observers to it and we are feeding some values to the Subject. On emitting the first value both the subscribers receive at the same time.