harness-drone/eventbus/builtin/bus.go

51 lines
962 B
Go
Raw Normal View History

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