Commit da928b0
Changed files (4)
pkg/event/aggregator.go
@@ -1,16 +1,25 @@
package event
-type Event any
-type Subscription func(any)
+import "github.com/xlgmokha/x/pkg/x"
type Aggregator struct {
subscriptions map[Event][]Subscription
}
func New() *Aggregator {
- return &Aggregator{
- subscriptions: map[Event][]Subscription{},
- }
+ 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) {
pkg/event/event.go
@@ -0,0 +1,3 @@
+package event
+
+type Event any
pkg/event/subscription.go
@@ -0,0 +1,3 @@
+package event
+
+type Subscription func(any)
pkg/event/typed_aggregator.go
@@ -1,17 +1,23 @@
package event
+import "github.com/xlgmokha/x/pkg/x"
+
type TypedAggregator[T any] struct {
aggregator *Aggregator
}
func NewAggregator[T any]() *TypedAggregator[T] {
- return NewWith[T](New())
+ return NewWith[T](x.New(WithoutSubscriptions()))
}
func NewWith[T any](aggregator *Aggregator) *TypedAggregator[T] {
- return &TypedAggregator[T]{
- aggregator: aggregator,
- }
+ return x.New[*TypedAggregator[T]](WithAggregator[T](aggregator))
+}
+
+func WithAggregator[T any](aggregator *Aggregator) x.Option[*TypedAggregator[T]] {
+ return x.With(func(item *TypedAggregator[T]) {
+ item.aggregator = aggregator
+ })
}
func (a *TypedAggregator[T]) SubscribeTo(event Event, f func(T)) {
@@ -20,7 +26,6 @@ func (a *TypedAggregator[T]) SubscribeTo(event Event, f func(T)) {
f(item)
}
})
-
}
func (a *TypedAggregator[T]) Publish(event Event, message T) {