Is there a method to retrieve the last value from an EventEmmiter
immediately after subscribing to it?
The scenario in question involves a list component that utilizes two additional components: a filter and a grid. The filter emits a filter
event, while the grid emits a sorting
event.
In the list component, I aim to implement the following code:
Observable
.combineLatest(filtering$, sorting$)
.switchMap(([filter, sorting]) => {
return this.api.list(filter, sorting);
})
...
This is concise and elegant code but encounters two issues:
EventEmitter
is not treated as an observable, though easily remedied by wrapping it with an observable.- The API call won't execute until every observable triggers at least once, posing a significant problem.
To address this, I currently utilize a BehaviorSubject
from RxJs:
Represents a value that changes over time. Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
In the filter component, I have implemented:
class UsersListFilter {
private filteringSource = new BehaviorSubject<UserFilter>(new UserFilter());
filtering$ = this.filteringSource.asObservable();
...
}
And within the list component:
class UsersList {
@ViewChild(UsersListFilter) private filter: UsersListFilter;
...
setupDataReloading() {
Observable
.combineLatest(this.filter.filtering$, this.grid.sorting$)
...
}
}
As depicted, I avoid using EventEmitter
altogether. Nonetheless, this solution doesn't align seamlessly with Angular2's conventional approach to child component interaction (@Output
).
Your insights are welcome.