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