Angular 2 Event emitters vs Subject
AngularAngular Problem Overview
In Angular 2 what is the difference between Event Emitter and Subject for announcing an event? It seems like event emitters are less complicated to declare....Which way is preferred by Angular 2?
dataRefreshEvent = new EventEmitter();
private companyDataAnnouncedSource = new Subject();
companyDataAnnouncedSource$ = this.companyDataAnnouncedSource.asObservable();
Angular Solutions
Solution 1 - Angular
There is not much difference. EventEmitter
extends Subject
.
The Angular2 team stressed the fact though, that EventEmitter
should not be used for anything else then @Output()
s in components and directives.
The Angular team has stated that they may change the underlying implementation of EventEmitter
and break user code that uses EventEmitter
for something it wasn't intended for. That's the main difference.
Solution 2 - Angular
Also EventEmitter
gets cleaned up automatically unlike custom Subjects
that you need to unsubscribe to in the onDestroy
lifecycle hook.
Solution 3 - Angular
EventEmitter by default is synchronous, whereas Subject is not. You can pass a flag to EventEmitter to make it asynchronous.
Solution 4 - Angular
EventEmitter
and Subjects
serve the same purpose - to notify about an event to an observer.
But EventEmitter
should only be used to notify an event from the child to the parent i.e., it should only be used with @Output()
.
To notify about an event across different components, Subjects
should be preferred. Subjects emit the value from one component and any other component can subscribe to it and it'll get notified.