Skip to content

Instantly share code, notes, and snippets.

@amix
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amix/9507950 to your computer and use it in GitHub Desktop.
Save amix/9507950 to your computer and use it in GitHub Desktop.
Observer pattern in Go - with channel specific locking
import "sync"
type Channel struct {
...
messages []*Message
listeners []chan *Message
sync.Mutex
}
...
// Notify
func (c *Channel) Notify(msg *Message) {
for _, ch := range c.listeners {
ch <- msg
}
}
// Subscribe
func (c *Channel) Subscribe(listener chan *Message) {
c.Lock()
defer c.Unlock()
c.listeners = append(c.listeners, listener)
}
// Unsubscribe
func (c *Channel) Unsubscribe(listener chan *Message) {
c.Lock()
defer c.Unlock()
newArray := make([]chan *Message, 0)
for _, ch := range c.listeners {
if ch != listener {
newArray = append(newArray, ch)
} else {
close(ch)
}
}
c.listeners = newArray
}
func TestSubscribeNotify(t *testing.T) {
someChan := new(Channel)
listner := make(chan *Message)
someChan.Subscribe(listner)
msg := &Message{1, "Hello world"}
go someChan.AddMessage(msg)
sameMsg := <- listner
if sameMsg != msg {
t.Error("Message should be the same")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment