Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper use of async EventEmitters?

Tags:

angular

I noticed that an EventEmitter can be configured to emit events asynchronously.

constructor(isAsync: boolean = false)
Creates an instance of EventEmitter, which depending on isAsync, delivers events synchronously or asynchronously.

(taken from https://angular.io/api/core/EventEmitter)

When should my component deliver events asynchronously instead of using the default behavior?

like image 364
Steven Liekens Avatar asked Nov 13 '17 10:11

Steven Liekens


1 Answers

When you are using the isAsync option then every event emitted from EventEmitter gets wrapped in setTimeout making it async.

This is excerpt from the EventEmitter source code:

this.__isAsync ? 
  (value: any) => { setTimeout(() => generatorOrNext.next(value)); } :
  (value: any) => { generatorOrNext.next(value); };

What value does it add to you? Probably none. Zone's checks will happen before your code receives event, and then again once your event has been processed creating more work for the CPUs. Theoretically you could squeeze some custom stuff in between, but even angular team does not recommend it.

Read more on reasoning here: https://github.com/angular/angular/issues/6311

Hope that helps

like image 120
Miroslav Jonas Avatar answered Nov 01 '22 06:11

Miroslav Jonas