When to use Observable vs EventEmitter vs Dot Rule for change detection in angular2

Let’s try to give you some hints…

The main problem with the last approach is that it doesn’t work with primitive types but only with references. So I wouldn’t recommend it…

I think that EventEmitter / Observable is the right approach to implement and handle custom events. It’s also linked to components themselves (@Ouput), bidirectional mapping in templates (syntax [(...)]) and the async pipe.

From the documentation, the EventEmitter uses Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec. After looking at the EventEmitter class of Angular2, it extends the Subject class. It’s a bit more than a simple Observable. See this link for more details: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

Regarding the creation of a custom observable, I would say: create your own observables only when you need something specific. Otherwise leverage the EventEmitter class. But there is a lot of things that you can do with the EventEmitter class and observable operators.

To conclude, on such a “simple” use case, things aren’t so obvious but on more complex scenarios, EventEmitter / Observable allow to define an handling chain using operators. The classical sample is to update a list according to a value for an input (here this.term defined in the ngModel of the field):

this.term.valueChanges
     .debounceTime(400)
     .flatMap(term => this.dataService.getItems(term))
     .subscribe(items => this.items = items);

This great blog post from Christoph Burgdorf could give you some ideas about what observables can handle: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html.

Hope it helps you,
Thierry

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)