2015-09-30 01:21:17 +00:00
|
|
|
package engine
|
2015-04-08 05:46:05 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2015-09-30 01:21:17 +00:00
|
|
|
type eventbus struct {
|
2015-04-08 05:46:05 +00:00
|
|
|
sync.Mutex
|
2015-09-30 01:21:17 +00:00
|
|
|
subs map[chan *Event]bool
|
2015-04-08 05:46:05 +00:00
|
|
|
}
|
|
|
|
|
2015-09-30 01:21:17 +00:00
|
|
|
// New creates a new eventbus that manages a list of
|
2015-04-08 05:46:05 +00:00
|
|
|
// subscribers to which events are published.
|
2015-09-30 01:21:17 +00:00
|
|
|
func newEventbus() *eventbus {
|
|
|
|
return &eventbus{
|
|
|
|
subs: make(map[chan *Event]bool),
|
2015-04-08 05:46:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Subscribe adds the channel to the list of
|
|
|
|
// subscribers. Each subscriber in the list will
|
|
|
|
// receive broadcast events.
|
2015-09-30 01:21:17 +00:00
|
|
|
func (b *eventbus) subscribe(c chan *Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
b.Lock()
|
|
|
|
b.subs[c] = true
|
|
|
|
b.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unsubscribe removes the channel from the
|
|
|
|
// list of subscribers.
|
2015-09-30 01:21:17 +00:00
|
|
|
func (b *eventbus) unsubscribe(c chan *Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
b.Lock()
|
|
|
|
delete(b.subs, c)
|
|
|
|
b.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send dispatches a message to all subscribers.
|
2015-09-30 01:21:17 +00:00
|
|
|
func (b *eventbus) send(event *Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
b.Lock()
|
|
|
|
defer b.Unlock()
|
|
|
|
|
2015-04-28 22:30:51 +00:00
|
|
|
for s := range b.subs {
|
2015-09-30 01:21:17 +00:00
|
|
|
go func(c chan *Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
defer recover()
|
|
|
|
c <- event
|
|
|
|
}(s)
|
|
|
|
}
|
|
|
|
}
|