added dispatcher.go

This commit is contained in:
Timo Volkmann 2020-11-07 12:19:00 +01:00
parent c511491229
commit edb74a66fd

39
dispatcher/dispatcher.go Normal file
View File

@ -0,0 +1,39 @@
package dispatcher
import "errors"
type Dispatcher struct {
listeners map[int16]chan string
counter int16
}
func New() Dispatcher {
return Dispatcher{
listeners: map[int16]chan string{},
counter: 0,
}
}
func (d *Dispatcher) Publish(message string) {
for _, ch := range d.listeners {
ch <- message
}
}
func (d *Dispatcher) Subscribe() (id int16, receiver <-chan string) {
key := d.counter
d.counter++
rec := make(chan string)
d.listeners[key] = rec
return key, rec
}
func (d *Dispatcher) Unsubscribe(id int16) error {
receiver, ok := d.listeners[id]
if !ok {
return errors.New("no subscription with id")
}
delete(d.listeners, id)
close(receiver)
return nil
}