summaryrefslogtreecommitdiff
path: root/pkg/event/aggregator.go
blob: 996a550cb357990b9ef1516800303d13e3df7ce4 (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
package event

import "github.com/xlgmokha/x/pkg/x"

type Aggregator struct {
	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.subscriptions[event] = append(a.subscriptions[event], f)
}

func (a *Aggregator) Publish(event Event, message any) {
	for _, subscription := range a.subscriptions[event] {
		subscription(message)
	}
}