I have a question about unsubscribing Output
s in Angular. I know that EventEmitter gets cleaned up automatically, but the last time I needed use Observable
as my Output
. I mean, I wanted take Output
which emit maximum once event per second. So my code looked like:
@Output() loadNextEvent: Observable<any>;
loadNextSubject = new Subject();
constructor(private el: ElementRef) {
this.loadNextEvent = this.loadNextSubject.asObservable()
.throttleTime(1000); // once per second
}
emit() {
this.loadNextSubject.next('new event');
}
Ok, it works pretty fine - I thought. The only problem is unsubscribing. I found one solution on StackOverflow, but I'm still not sure, how I should do it correctly. In my case:
@Output() loadNextEvent: Observable<any>;
loadNextSubject = new Subject();
constructor(private el: ElementRef) {
this.loadNextEvent = this.loadNextSubject.asObservable()
.takeUntil(this.loadNextSubject) //does it make any sense?
.throttleTime(1000); // once per second
}
emit() {
this.loadNextSubject.next('new event');
}
ngOnDestroy() {
this.loadNextSubject.complete();
}
Question:
Is this the correct unsubscribing of observable Output
? .takeUntil(this.loadNextSubject)
make any sense? Or maybe .asObservable()
give ensurance that Observable was cleaned, when Subject
is completed? Anyone know answer for my problem? or maybe, there is a better solution, then use Observable
as Output
, for my case?