main
1package event
2
3import (
4 "sync"
5
6 "github.com/xlgmokha/x/pkg/x"
7)
8
9type Aggregator struct {
10 mu sync.RWMutex
11 subscriptions map[Event][]Subscription
12}
13
14func WithDefaults() x.Option[*Aggregator] {
15 return x.With(func(item *Aggregator) {
16 item.mu = sync.RWMutex{}
17 item.subscriptions = map[Event][]Subscription{}
18 })
19}
20
21func (a *Aggregator) Subscribe(event Event, f Subscription) {
22 a.mu.Lock()
23 defer a.mu.Unlock()
24
25 a.subscriptions[event] = append(a.subscriptions[event], f)
26}
27
28func (a *Aggregator) Publish(event Event, message any) {
29 a.mu.RLock()
30 defer a.mu.RUnlock()
31
32 for _, subscription := range a.subscriptions[event] {
33 subscription(message)
34 }
35}