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

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

type Aggregator struct {
	subscriptions map[Event][]Subscription
}

func New() *Aggregator {
	return x.New[*Aggregator](
		WithoutSubscriptions(),
	)
}

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)
	}
}