package hub
import "sync"
type Kind int
type Event interface {
Kind () Kind
}
type Hub struct {
subscribers map [Kind ][]handler
m sync .RWMutex
seq uint64
}
type handler struct {
f func (Event )
id uint64
}
func (h *Hub ) Subscribe (kind Kind , f func (Event )) (cancel func ()) {
var cancelled bool
h .m .Lock ()
h .seq ++
id := h .seq
if h .subscribers == nil {
h .subscribers = make (map [Kind ][]handler )
}
h .subscribers [kind ] = append (h .subscribers [kind ], handler {id : id , f : f })
h .m .Unlock ()
return func () {
h .m .Lock ()
if cancelled {
h .m .Unlock ()
return
}
cancelled = true
a := h .subscribers [kind ]
for i , f := range a {
if f .id == id {
a [i ], h .subscribers [kind ] = a [len (a )-1 ], a [:len (a )-1 ]
break
}
}
if len (a ) == 0 {
delete (h .subscribers , kind )
}
h .m .Unlock ()
}
}
func (h *Hub ) Publish (e Event ) {
h .m .RLock ()
if handlers , ok := h .subscribers [e .Kind ()]; ok {
for _ , h := range handlers {
h .f (e )
}
}
h .m .RUnlock ()
}
var DefaultHub Hub
func Subscribe (kind Kind , f func (Event )) (cancel func ()) {
return DefaultHub .Subscribe (kind , f )
}
func Publish (e Event ) {
DefaultHub .Publish (e )
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .