-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifier.go
63 lines (57 loc) · 1.58 KB
/
notifier.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package sagas
import (
"context"
"sync"
)
// Notifier is an interface that represents a Notifier. It is responsible for
// notifying the observers that a notification occurred.
type Notifier interface {
// Add adds an observer to the Notifier.
Add(observer Observer)
// Notify send to all observers in parallel that an notification occurred.
Notify(ctx context.Context, notification Notification)
}
// notifier is the concrete implementation of the Notifier interface.
type notifier struct {
observers []Observer
}
// NewNotifier returns a new notifier. It returns a Notifier.
// Example:
//
// identifier := sagas.Identifier("identifier")
//
// notification, err := sagas.NewNotification(identifier, sagas.Completed)
//
// executionPlan := sagas.NewExecutionPlan()
//
// observer := sagas.NewObserver(executionPlan)
//
// notifier := sagas.NewNotifier()
//
// notifier.Add(observer)
//
// notifier.Notify(context.Background(), notification)
//
// The above example will create a new notifier and notify the observers that a
// notification occurred.
func NewNotifier() Notifier {
return ¬ifier{
observers: make([]Observer, 0),
}
}
// Add adds an observer to the Notifier. Example:
func (n *notifier) Add(observer Observer) {
n.observers = append(n.observers, observer)
}
// Notify send to all observers in parallel that an notification occurred.
func (n *notifier) Notify(ctx context.Context, notification Notification) {
wg := sync.WaitGroup{}
for _, obs := range n.observers {
wg.Add(1)
go func(o Observer) {
defer wg.Done()
o.Execute(ctx, notification)
}(obs)
}
wg.Wait()
}