-
Notifications
You must be signed in to change notification settings - Fork 5
/
eventer.go
60 lines (43 loc) · 1.17 KB
/
eventer.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
package batcher
import (
"sync"
"github.com/google/uuid"
)
type eventer struct {
listenerMutex sync.RWMutex
listeners map[uuid.UUID]func(event string, val int, msg string, metadata interface{})
}
type ieventer interface {
AddListener(fn func(event string, val int, msg string, metadata interface{})) uuid.UUID
RemoveListener(id uuid.UUID)
emit(event string, val int, msg string, metadata interface{})
}
func (r *eventer) AddListener(fn func(event string, val int, msg string, metadata interface{})) uuid.UUID {
// lock
r.listenerMutex.Lock()
defer r.listenerMutex.Unlock()
// allocate
if r.listeners == nil {
r.listeners = make(map[uuid.UUID]func(event string, val int, msg string, metadata interface{}))
}
// add a new listener
id := uuid.New()
r.listeners[id] = fn
return id
}
func (r *eventer) RemoveListener(id uuid.UUID) {
// lock
r.listenerMutex.Lock()
defer r.listenerMutex.Unlock()
// remove
delete(r.listeners, id)
}
func (r *eventer) emit(event string, val int, msg string, metadata interface{}) {
// lock
r.listenerMutex.RLock()
defer r.listenerMutex.RUnlock()
// emit
for _, fn := range r.listeners {
fn(event, val, msg, metadata)
}
}