Table of Contents generated with DocToc
-- import "github.com/reaandrew/telegraph"
type LinkedPublisher struct {
}LinkedPublisher is the struct which provides the publish and subscribe behaviour
func NewLinkedPublisher() LinkedPublisherNewLinkedPublisher returns a new instance of a LinkedPublisher
func (instance LinkedPublisher) Publish(notification interface{})Publish iterates over the list of channels and sends the notification object
func (instance LinkedPublisher) Subscribe() SubscriptionSubscribe creates a new channel and adds it to the publisher. It returns a Subscription struct which exposes a Channel member to consume
func (instance LinkedPublisher) Unsubscribe(subscription *list.Element)Unsubscribe removes the channel from the list and also closes it The channel can not longer be used.
type Subscription struct {
Channel <-chan interface{}
}Subscription struct is the main type used to subscibe The Channel member is used to receive published messages
func (instance Subscription) RemoveFrom(publisher LinkedPublisher)RemoveFrom invokes the Publisher with its hidden copy of the Element. This allows the Publisher to efficiently maintain its list of subscribers whilst maintain encapsulation
broadcaster := NewLinkedPublisher()
subscription := broadcaster.Subscribe()
go func() {
broadcaster.Publish(1)
}()
Expect(<-subscription.Channel).To(Equal(1))broadcaster := NewLinkedPublisher()
subscriptionOne := broadcaster.Subscribe()
subscriptionTwo := broadcaster.Subscribe()
subscriptionOne.RemoveFrom(broadcaster)
go func() {
broadcaster.Publish(2)
}()
Expect(<-subscriptionTwo.Channel).To(Equal(2))broadcaster := NewLinkedPublisher()
subscriptionOne := broadcaster.Subscribe()
if subscriptionOne.Channel != nil {
//Do somthing
}
subscriptionTwo := broadcaster.Subscribe()
go func() {
broadcaster.Publish(3)
}()
Expect(<-subscriptionTwo.Channel).To(Equal(3))broadcaster := NewLinkedPublisher()
subscription := broadcaster.Subscribe()
go func() {
for i := 0; i < 10; i++ {
broadcaster.Publish(i + 1)
}
}()
for i := range subscription.Channel {
if i.(int) == 10 {
subscription.RemoveFrom(broadcaster)
}
}
fmt.Println("You will see this message!")