title: service listeners in angular
body: <p>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 <code>ListenerCollection</code> class.</p>
  
  <pre><code>@Injectable()
  export class SomeService {
    public listeners: ListenerCollection = new ListenerCollection();
  }
  </code></pre>
  
  <p>The <code>ListenerCollection</code> holds a set of listeners internally. It has multiple usages, one of them being this specific service.</p>
  
  <pre><code>export class ListenerCollection {
    private listeners: Set&lt;any&gt; = new Set&lt;any&gt;();
  
    constructor() {}
  
    public addListener(listener) {
      this.listeners.add(listener);
    }
  
    public removeListener(listener) {
      this.listeners.delete(listener);
    }
  
    public notifyListeners(param: any) {
      const listeners: Iterable&lt;any&gt; = this.listeners.values();
      for (const listener of listeners) {
        listener(param);
      }
    }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>So, this got me wondering, what would be the Angular way of doing this?</p>