简体   繁体   English

异步EventEmitter的用例

[英]Use case for async EventEmitter

I noticed that it is possible to create sync or async EventEmitters in Angular. 我注意到可以在Angular中创建同步或异步EventEmitters。 As far as I see, default is sync. 据我所知,默认为同步。

https://github.com/angular/angular/blob/master/packages/core/src/event_emitter.ts 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). 据我所知,同步意味着事件处理程序(generatorOrNext,错误和完整)是在与事件生成相同的更改检测周期中执行的,而异步意味着事件处理程序是在另一更改检测中执行的循环(因为处理程序包装在触发更改检测的setTimeout方法中)。

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? 也许有人可以给我一个简短的具体用例?

I think you are right, because when you call .emit() in async mode it will: 我认为您是对的,因为在异步模式下调用.emit()时,它将:

 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. 因此,区别在于, 如果您使用sync事件发射器则在调用embed()和正在执行的订阅者之间不会有更改检测 ,这在某些情况下可能很重要,例如,当您想要更新@Inputs在调用事件发射器订阅者处理程序之前。 Hope that makes any sense. 希望有任何道理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM