I have a service that provides realtime data to multiple listening components. There is only one instance of the service, and it stores its listeners internally using a ListenerCollection
class.
@Injectable()
export class SomeService {
public listeners: ListenerCollection = new ListenerCollection();
}
The ListenerCollection
holds a set of listeners internally. It has multiple usages, one of them being this specific service.
export class ListenerCollection {
private listeners: Set<any> = new Set<any>();
constructor() {}
public addListener(listener) {
this.listeners.add(listener);
}
public removeListener(listener) {
this.listeners.delete(listener);
}
public notifyListeners(param: any) {
const listeners: Iterable<any> = this.listeners.values();
for (const listener of listeners) {
listener(param);
}
}
}
Now, it works excellent. But I don't like the fact that I have to create a custom class to store and notify the listeners. My gut feeling tells me that something already exists for this.
So, this got me wondering, what would be the Angular way of doing this?