This commit is contained in:
parent
6dc923b6ae
commit
56485330dd
21
bus.go
21
bus.go
|
@ -1,5 +1,7 @@
|
|||
package events
|
||||
|
||||
import "sync"
|
||||
|
||||
type Bus struct {
|
||||
topics map[string]*topic
|
||||
}
|
||||
|
@ -12,7 +14,7 @@ func (d *Bus) On(event string, receiver interface{}) *Subscription {
|
|||
// TODO: make thread safe
|
||||
t, hasTopic := d.topics[event]
|
||||
if !hasTopic {
|
||||
t = &topic{}
|
||||
t = &topic{mutex: sync.Mutex{}, head: nil, tail: nil}
|
||||
d.topics[event] = t
|
||||
}
|
||||
|
||||
|
@ -38,12 +40,17 @@ func (d *Bus) TryFire(event string, args ...interface{}) error {
|
|||
|
||||
preparedArgs := prepareArgs(args)
|
||||
|
||||
topic.mutex.Lock()
|
||||
var head = topic.head
|
||||
topic.mutex.Unlock()
|
||||
|
||||
var errs []error
|
||||
|
||||
var lastSub *Subscription = nil
|
||||
for sub := topic.head; sub != nil; sub = sub.next {
|
||||
for sub := head; sub != nil; sub = sub.next {
|
||||
// Remove unsubscribers
|
||||
if sub.remove {
|
||||
topic.mutex.Lock()
|
||||
if lastSub == nil {
|
||||
topic.head = sub.next
|
||||
} else {
|
||||
|
@ -52,6 +59,7 @@ func (d *Bus) TryFire(event string, args ...interface{}) error {
|
|||
if topic.tail == sub {
|
||||
topic.tail = lastSub
|
||||
}
|
||||
topic.mutex.Unlock()
|
||||
continue
|
||||
}
|
||||
lastSub = sub
|
||||
|
@ -72,11 +80,16 @@ func (d *Bus) TryFire(event string, args ...interface{}) error {
|
|||
}
|
||||
|
||||
type topic struct {
|
||||
head *Subscription
|
||||
tail *Subscription
|
||||
// mutex protects writes to the head and tail
|
||||
mutex sync.Mutex
|
||||
head *Subscription
|
||||
tail *Subscription
|
||||
}
|
||||
|
||||
func (t *topic) addSubscriber(sub *Subscription) {
|
||||
t.mutex.Lock()
|
||||
defer t.mutex.Unlock()
|
||||
|
||||
if t.head == nil {
|
||||
t.head = sub
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue