-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatcher.go
49 lines (37 loc) · 858 Bytes
/
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
package event
import (
"fmt"
)
type Dispatcher struct {
jobs chan job
events map[Name]Listener
}
func NewDispatcher() *Dispatcher {
d := &Dispatcher{
jobs: make(chan job),
events: make(map[Name]Listener),
}
go d.consume()
return d
}
func (d *Dispatcher) Register(listener Listener, names ...Name) error {
for _, name := range names {
if _, ok := d.events[name]; ok {
return fmt.Errorf("the '%s' event is already registered", name)
}
d.events[name] = listener
}
return nil
}
func (d *Dispatcher) Dispatch(name Name, event interface{}) error {
if _, ok := d.events[name]; !ok {
return fmt.Errorf("the '%s' event is not registered", name)
}
d.jobs <- job{eventName: name, eventType: event}
return nil
}
func (d *Dispatcher) consume() {
for job := range d.jobs {
d.events[job.eventName].Listen(job.eventType)
}
}