Reputation: 7088
I noticed that it is possible to create sync or async EventEmitters in Angular. As far as I see, default is sync.
https://github.com/angular/angular/blob/master/packages/core/src/event_emitter.ts
As far as I think I understand, sync means that the event handlers (generatorOrNext, error, and the complete) are executed in the same change detection cycle as the event is generated, while async means that the event handlers are executed in another change detection cycle (because handlers are wrapped in a setTimeout method which triggers change detection).
I can not think of a concrete use case when the async behavior would be an advantage (probably some performance related use case)? Maybe someone can give me a short concrete use case?
Upvotes: 5
Views: 411
Reputation: 3699
I think you are right, because when you call .emit() in async mode it will:
1. Set up timeout inside event emitter (but nothing would be emitted).
2. Your current zone context turn ends, angular change detection happens.
3. Timeout's callback in event emitter triggers, which emits value and calls all subscribers of current event emitter.
4. And after all subscribers have been called, it runs change detection again.
So the difference is that you won't have change detection between you call emit() and your subscribers being executed if you use sync event emitter, that could be important in some scenarios when, for example, you want your @Inputs to be updated before your event emitter subscriber handler would be called. Hope that makes any sense.
Upvotes: 2