Documentation ¶
Overview ¶
PubSub package provides simple mechanism to implement publisher subscriber relation.
type Timer struct { pubsub.Publisher } timer := new(Timer) go func() { for { time.Sleep(time.Second) timer.Publish(time.Now()) } }() reader, _ := timer.SubReader() for { fmt.Println(reader.Read()) }
Memory considerations: memory consumption increases if subscribers do not consume messages as fast as published by Publisher. There's no need to unsubscribe explicitelly, once SubReader reference is lost GC takes care of it. The same applies to subscription channel.
You might want to hide Publish method in composition scenarios:
type Timer struct { p pubsub.Publisher }
In that case you need to provide access to SubReader and SubChannel methods:
func (t *Timer) SubReader() (pubsub.Reader, interface{}) { return t.p.SubReader() }
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Publisher ¶
type Publisher struct {
// contains filtered or unexported fields
}
Publisher is used to publish messages. Can be directly created.
Example ¶
package main import ( "fmt" "github.com/igm/pubsub" ) func main() { pub := pubsub.Publisher{} ch, _ := pub.SubChannel(nil) pub.Publish("msg 1") pub.Publish("msg 2") fmt.Println(<-ch) fmt.Println(<-ch) }
Output: msg 1 msg 2
Example (Composition) ¶
package main import ( "fmt" "github.com/igm/pubsub" ) func main() { type StockExchange struct { pubsub.Publisher } se := new(StockExchange) ch, _ := se.SubChannel(nil) se.Publish("msg 1") se.Publish("msg 2") fmt.Println(<-ch) fmt.Println(<-ch) }
Output: msg 1 msg 2
func (*Publisher) Publish ¶
func (p *Publisher) Publish(val interface{})
Publish publishes a message to all existing subscribers
func (*Publisher) SubChannel ¶
func (p *Publisher) SubChannel(finalMsg interface{}) (msgChan <-chan interface{}, lastMsg interface{})
SubChannel returns a new channel for reading published messages and a last published message. If published messages equals (==) finalMsg then channel is closed afer putting message into channel.
Example ¶
package main import ( "fmt" "github.com/igm/pubsub" ) func main() { pub := new(pubsub.Publisher) ch, _ := pub.SubChannel("close") pub.Publish("msg 1") pub.Publish("msg 2") pub.Publish("close") for msg := range ch { fmt.Println(msg) } }
Output: msg 1 msg 2 close
func (*Publisher) SubReader ¶
SubReader returns a new reader for reading published messages and a last published message.
Example ¶
package main import ( "fmt" "github.com/igm/pubsub" "time" ) func main() { type Timer struct { pubsub.Publisher } timer := new(Timer) go func() { for /*...*/ { time.Sleep(time.Second) timer.Publish(time.Now()) // ... } }() reader, _ := timer.SubReader() for { fmt.Println(reader.Read()) } }
Output: