Skip to content

reaandrew/telegraph

Repository files navigation

Build Status Coverage Status

Table of Contents generated with DocToc

telegraph

-- import "github.com/reaandrew/telegraph"

Usage

type LinkedPublisher

type LinkedPublisher struct {
}

LinkedPublisher is the struct which provides the publish and subscribe behaviour

func NewLinkedPublisher

func NewLinkedPublisher() LinkedPublisher

NewLinkedPublisher returns a new instance of a LinkedPublisher

func (LinkedPublisher) Publish

func (instance LinkedPublisher) Publish(notification interface{})

Publish iterates over the list of channels and sends the notification object

func (LinkedPublisher) Subscribe

func (instance LinkedPublisher) Subscribe() Subscription

Subscribe creates a new channel and adds it to the publisher. It returns a Subscription struct which exposes a Channel member to consume

func (LinkedPublisher) Unsubscribe

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

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 (Subscription) RemoveFrom

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

Examples

Subscribing

broadcaster := NewLinkedPublisher()
subscription := broadcaster.Subscribe()
go func() {
  broadcaster.Publish(1)
}()
Expect(<-subscription.Channel).To(Equal(1))

Unsubscribing

broadcaster := NewLinkedPublisher()
subscriptionOne := broadcaster.Subscribe()
subscriptionTwo := broadcaster.Subscribe()
subscriptionOne.RemoveFrom(broadcaster)
go func() {
  broadcaster.Publish(2)
}()
Expect(<-subscriptionTwo.Channel).To(Equal(2))

Non blocking publications

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))

Ending a range after Unsubscribing

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!")

About

Simple implementation pub sub in golang

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages