Documentation
¶
Overview ¶
Package broadcaster allows broadcasting a value over many channels at once.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Caster ¶
type Caster interface {
// Subscribe will return a channel that recieves broadcasted messages, along
// with a done channel that unsubscribes and closes the broadcast channel
// when closed. When unsubscribing, any messages currently pending will still
// still be attempting to send until after the WaitTime.
Subscribe(done <-chan struct{}) <-chan interface{}
// Cast sends a message to be broadcast to all subscribers.
Cast(msg interface{})
// Close closes all created channels. Further calls to Close or Cast will
// panic, and further subscriptions will return a closed channel.
Close()
}
Caster allows sending messages to many subscribed channels.
Example ¶
package main
import (
"fmt"
"sync"
"github.com/stvnrhodes/broadcaster"
)
func main() {
// Create a new broadcaster
b := broadcaster.New()
// Create a channel subscribed to the broadcaster
done := make(chan struct{})
ch := b.Subscribe(done)
// Wait groups are added to make the example more deterministic.
// In most cases, having no wait groups is fine.
var wg, wg2 sync.WaitGroup
wg.Add(1)
wg2.Add(1)
// Read all messages from the channel.
go func() {
for msg := range ch {
fmt.Println("Hello", msg)
}
wg.Done()
}()
b.Cast("World")
// Create another channel. This one won't unsubscribe, so the argument is nil.
ch2 := b.Subscribe(nil)
// Read all messages from the channel.
go func() {
for msg := range ch2 {
fmt.Println("Goodbye", msg)
}
wg2.Done()
}()
// Cast to the channel
b.Cast(123)
close(done)
wg.Wait()
b.Cast("examples")
b.Close()
wg2.Wait()
}
Output: Hello World Hello 123 Goodbye 123 Goodbye examples
Click to show internal directories.
Click to hide internal directories.
