Documentation
¶
Overview ¶
Package pubsub provides a simple publish/subscribe mechanism.
It supports both synchronous and asynchronous subscriptions.
Example ¶
// Create a new topic.
t := New[int]()
// Subscribe to changes.
changes := t.Subscribe(nil)
go func() {
for change := range changes {
fmt.Println("change:", change)
}
}()
// Publish a value.
t.Publish(1)
// Publish a value and wait for it to be received.
t.Publish(2)
time.Sleep(time.Millisecond * 100)
Output: change: 1 change: 2
Index ¶
- Constants
- type Message
- type Topic
- func (s *Topic[T]) Close() error
- func (s *Topic[T]) Publish(t T)
- func (s *Topic[T]) PublishSync(t T) error
- func (s *Topic[T]) Subscribe(c chan T) chan T
- func (s *Topic[T]) SubscribeSync(c chan Message[T]) chan Message[T]
- func (s *Topic[T]) Unsubscribe(c chan T)
- func (s *Topic[T]) UnsubscribeSync(c chan Message[T])
- func (s *Topic[T]) Wait() chan struct{}
Examples ¶
Constants ¶
const AckTimeout = time.Second * 30
AckTimeout is the time to wait for an ack before panicking.
This is a last-ditch effort to avoid deadlocks.
const PublishTimeout = time.Second * 10
PublishTimeout is the time to wait for a publish before panicking.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Message ¶ added in v0.12.0
type Message[T any] struct { Msg T // contains filtered or unexported fields }
Message is a message that must be acknowledge by the receiver.
type Topic ¶
type Topic[T any] struct { // contains filtered or unexported fields }
func (*Topic[T]) PublishSync ¶ added in v0.12.0
PublishSync publishes a message to the topic and blocks until all subscriber channels have acked the message.
func (*Topic[T]) Subscribe ¶
func (s *Topic[T]) Subscribe(c chan T) chan T
Subscribe a channel to the topic.
The channel will be closed when the topic is closed.
If "c" is nil a new channel of size 16 will be created.
func (*Topic[T]) SubscribeSync ¶ added in v0.12.0
SubscribeSync creates a synchronous subscription to the topic.
Each message must be acked by the subscriber.
A synchronous publish will block until the message has been acked by all subscribers.
The channel will be closed when the topic is closed. If "c" is nil a new channel of size 16 will be created.
func (*Topic[T]) Unsubscribe ¶
func (s *Topic[T]) Unsubscribe(c chan T)
Unsubscribe a channel from the topic, closing the channel.
func (*Topic[T]) UnsubscribeSync ¶ added in v0.12.0
UnsubscribeSync a synchronised subscription from the topic, closing the channel.