Last active
August 29, 2015 13:57
-
-
Save amix/9507950 to your computer and use it in GitHub Desktop.
Observer pattern in Go - with channel specific locking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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