added dispatcher.go
This commit is contained in:
parent
c511491229
commit
edb74a66fd
39
dispatcher/dispatcher.go
Normal file
39
dispatcher/dispatcher.go
Normal 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
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user