Initial Bus implementation

This commit is contained in:
Ian Gulliver
2022-03-15 16:27:52 +00:00
parent eb60a6aacf
commit 88c24f1a40
5 changed files with 120 additions and 69 deletions

50
bus.go Normal file
View File

@@ -0,0 +1,50 @@
package main
import "sync"
type Bus struct {
mu sync.Mutex
chans map[string][]chan Object
}
func NewBus() *Bus {
return &Bus{
chans: map[string][]chan Object{},
}
}
func (b *Bus) Announce(obj Object) {
key := ObjectKey(obj)
b.mu.Lock()
defer b.mu.Unlock()
chans := b.chans[key]
newChans := []chan Object{}
for _, ch := range chans {
select {
case ch <- obj:
newChans = append(newChans, ch)
default:
close(ch)
}
}
if len(chans) != len(newChans) {
b.chans[key] = newChans
}
}
func (b *Bus) Subscribe(obj Object) chan Object {
key := ObjectKey(obj)
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan Object, 100)
b.chans[key] = append(b.chans[key], ch)
return ch
}