Documentation ¶
Overview ¶
Package broadcast implements multi-listener broadcast channels with generic type T. See https://pkg.go.dev/github.com/textileio/go-threads/broadcast for non-generic type implementation. See https://godoc.org/github.com/tjgq/broadcast for original implementation.
To create an un-buffered broadcast channel, just declare a Broadcaster:
var b broadcast.Broadcaster[string]
To create a buffered broadcast channel with capacity n, call New:
b := broadcast.New[string](n)
To add a listener to a channel, call Listen and read from Channel():
l := b.Listen() for v := range l.Channel() { // ... }
To send to the channel, call Send:
b.Send("Hello world!") v <- l.Channel() // returns "Hello world!"
To remove a listener, call Discard.
l.Discard()
To close the broadcast channel, call Discard. Any existing or future listeners will read from a closed channel:
b.Discard() v, ok <- l.Channel() // returns ok == false
Index ¶
Constants ¶
const ErrClosedChannel = broadcastError("send after close")
ErrClosedChannel means the caller attempted to send to one or more closed broadcast channels.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Broadcaster ¶
type Broadcaster[T any] struct { // contains filtered or unexported fields }
Broadcaster implements a Publisher. The zero value is a usable un-buffered channel.
func NewBroadcaster ¶
func NewBroadcaster[T any](n int) *Broadcaster[T]
NewBroadcaster returns a new Broadcaster with the given capacity (0 means un-buffered).
func (*Broadcaster[T]) Discard ¶
func (b *Broadcaster[T]) Discard()
Discard closes the channel, disabling the sending of further messages.
func (*Broadcaster[T]) Listen ¶
func (b *Broadcaster[T]) Listen() *Listener[T]
Listen returns a Listener for the broadcast channel.
func (*Broadcaster[T]) Send ¶
func (b *Broadcaster[T]) Send(v T) error
Send broadcasts a message to each listener's channel. Sending on a closed channel causes a runtime panic. This method is non-blocking, and will return errors if unable to send on a given listener's channel.
func (*Broadcaster[T]) SendWithTimeout ¶
func (b *Broadcaster[T]) SendWithTimeout(v T, timeout time.Duration) error
SendWithTimeout broadcasts a message to each listener's channel. Sending on a closed channel causes a runtime panic. This method blocks for a duration of up to `timeout` on each channel. Returns error(s) if it is unable to send on a given listener's channel within `timeout` duration.
func (*Broadcaster[T]) SendWithoutTimeout ¶
func (b *Broadcaster[T]) SendWithoutTimeout(v T) error
SendWithoutTimeout broadcasts a message to each listener's channel. Sending on a closed channel causes a runtime panic. This method blocks until each listener received or error. This method will try to send message concurrently to each listener.