-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.go
71 lines (56 loc) · 1.28 KB
/
dispatcher.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
package event
import (
"sync"
"github.com/google/uuid"
)
type EventHandler func(e interface{})
type Dispatcher struct {
mu sync.RWMutex
callbacks map[string][]*Subscription
}
func NewDispatcher() *Dispatcher {
return &Dispatcher{
callbacks: make(map[string][]*Subscription),
}
}
func (d *Dispatcher) Subscribe(subject string, h EventHandler) *Subscription {
d.mu.Lock()
defer d.mu.Unlock()
sub := &Subscription{
subject: subject,
id: uuid.New().String(),
handler: h,
dispatcher: d,
}
d.callbacks[subject] = append(d.callbacks[subject], sub)
return sub
}
func (d *Dispatcher) Emit(subject string, v interface{}) {
d.mu.RLock()
defer d.mu.RUnlock()
if subs, ok := d.callbacks[subject]; ok {
for i := range subs {
go subs[i].handler(v)
}
}
}
func (d *Dispatcher) remove(subject string, id string) {
d.mu.Lock()
defer d.mu.Unlock()
for i, subscription := range d.callbacks[subject] {
if subscription.id == id {
d.callbacks[subject] = append(d.callbacks[subject][:i], d.callbacks[subject][i+1:]...)
break
}
}
}
func (d *Dispatcher) isValid(subject string, id string) bool {
d.mu.Lock()
defer d.mu.Unlock()
for _, subscription := range d.callbacks[subject] {
if subscription.id == id {
return true
}
}
return false
}