Angular component: Can I use an Observable instead EventEmitter as @Output() property?
EventEmitter
just extends Subject
, so this is no surprise (and I also saw this already in Dart).
They use their own class to be able to alter the implementation later without breaking existing code.
So it might not be the best idea to circumvent this abstraction. If you are aware of the disadvantage and willing to accept it, you can of course do it.
Well, in your situation you could use EventEmitter
or Subject
. You can see that an EventEmitter
is just like Subject
(although it's recommended to use EventEmitter
if you can). https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/async.ts
The Observable.create
(or new Observable()
) is not intended to be used like this. The inner function should emit values to the observer and return a tear down function (to release resources or whatever). Not to be kept as a property.
However, I'm not sure what consequences it might have (memory leaks?).
So rather use Subject
instead:
export class SplitComponent implements OnDestroy {
@Output() visibleTransitionEnd: Observable<string>
visibleTransitionEndObserver: Subject;
constructor() {
const subject = new Subject();
this.visibleTransitionEnd = subject.asObservable()
.map(x => '> ' + x + ' <')
.debounceTime(20)
.do(() => console.log('here we are!'));
}
// ...
}
2 reasons to choose EventEmitter
- Angular
EventEmitter
can make sure to delivery event asynchronously if needed. It's good for responsive user experience. - Encapsulate the underline implementation. If someday, next version of Angular would update event binding which depends on something new of
EventEmitter
. It would be disaster of your project ifSubject
extensively used. Not sure about this. But should be avoided.
Angular EventEmitter
extends RxJS Subject
with only 3 methods so far: 1) constructor()
, 2) subscribe(next, error, complete)
and 3) new method emit(value) {super.next(value);}
If you new EventEmitter(true)
, it will deliver events asynchronously
constructor(isAsync = false) {
super();
this.__isAsync = isAsync;
}
EventEmitter.subscribe()
does something to async delivery event according to this._isAsync
.