-
Notifications
You must be signed in to change notification settings - Fork 1
/
disposer.go
75 lines (68 loc) · 1.75 KB
/
disposer.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
64
65
66
67
68
69
70
71
72
73
74
75
package light
import "sync"
// Disposer provide accest to emiting and handling events
type Disposer struct {
handlers map[string][]EventHandler
subscribers []SubscribeHandler
subscribersMutex sync.RWMutex
}
// Handle adds handler to event by its name
func (m *Disposer) Handle(name string, handler EventHandler) {
if _, ok := m.handlers[name]; !ok {
m.handlers[name] = make([]func(Event) error, 0)
}
m.handlers[name] = append(m.handlers[name], handler)
}
// Subscribe adds handler to all emitted events
func (m *Disposer) Subscribe(subscriber SubscribeHandler) {
m.subscribersMutex.Lock()
m.subscribers = append(m.subscribers, subscriber)
m.subscribersMutex.Unlock()
}
// Emit emits event
func (m *Disposer) Emit(event Event) error {
m.subscribersMutex.RLock()
defer m.subscribersMutex.RUnlock()
for _, subscriber := range m.subscribers {
if err := subscriber(event); err != nil {
return err
}
}
if _, ok := m.handlers[event.Name]; !ok {
return nil
}
for _, handler := range m.handlers[event.Name] {
if err := handler(event); err != nil {
return err
}
}
return nil
}
// AsyncEmit emits event asynchronously
func (m *Disposer) AsyncEmit(event Event) {
m.subscribersMutex.RLock()
defer m.subscribersMutex.RUnlock()
for _, subscriber := range m.subscribers {
go func(subscriber SubscribeHandler) {
if err := subscriber(event); err != nil {
panic(err)
}
}(subscriber)
}
if _, ok := m.handlers[event.Name]; !ok {
return
}
for _, handler := range m.handlers[event.Name] {
go func(handler EventHandler) {
if err := handler(event); err != nil {
panic(err)
}
}(handler)
}
}
// NewDisposer creates disposer
func NewDisposer() Disposer {
return Disposer{
handlers: make(map[string][]EventHandler),
}
}