pubsub

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2024 License: MIT Imports: 1 Imported by: 3

Documentation

Overview

Package pubsub provides a simple publish/subscribe mechanism.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Topic

type Topic[T any] struct {
	// contains filtered or unexported fields
}

func New

func New[T any]() *Topic[T]

New creates a new topic that can be used to publish and subscribe to messages.

func (*Topic[T]) Close

func (s *Topic[T]) Close() error

Close the topic, blocking until all subscribers have been closed.

func (*Topic[T]) Publish

func (s *Topic[T]) Publish(t T)

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

func (s *Topic[T]) Unsubscribe(c chan T)

Unsubscribe a channel from the topic, closing the channel.

func (*Topic[T]) Wait added in v0.11.0

func (s *Topic[T]) Wait() chan struct{}

Wait that returns a channel that will be closed when the Topic is closed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL