/
notify.go
52 lines (44 loc) · 1.08 KB
/
notify.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
package gocchan
import "sync"
// Notifier represents a notifier of any event.
type Notifier struct {
listeners []Listener
mu sync.Mutex
wg sync.WaitGroup
}
// WaitNotify blocks until the all notifications of global notifier is finished.
func WaitNotify() {
notifier.Wait()
}
// NotifyAll notify event to all listeners.
func (n *Notifier) NotifyAll(event *Event) {
n.mu.Lock()
defer n.mu.Unlock()
for _, listener := range n.listeners {
n.wg.Add(1)
go func(listener Listener) {
defer n.wg.Done()
listener.Listen(event)
}(listener)
}
}
// Wait blocks until the all notifications is finished.
func (n *Notifier) Wait() {
n.wg.Wait()
}
// Listener is an interface of listener of event.
type Listener interface {
Listen(event *Event)
}
// global notifier.
var notifier = &Notifier{}
// AddEventListener adds a listener of event.
// If listener is nil, it panic.
func AddEventListener(listener Listener) {
if listener == nil {
panic("Add Listener is nil")
}
notifier.mu.Lock()
defer notifier.mu.Unlock()
notifier.listeners = append(notifier.listeners, listener)
}