bus

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2024 License: MIT Imports: 5 Imported by: 0

README

bus

A generic, thread-safe, highly optimized event bus for Go.

Install

go get github.com/webmafia/bus

Usage

const (
	Created bus.Topic = iota
	Updated
	Deleted
)

type User struct {
	Id   int
	Name string
}

// Create a new event bus with a buffer of 32 events
b := bus.NewBus(context.Background(), 32)

// Subscribe for created users
bus.SubVal(b, Created, func(ctx context.Context, u *User) {
	log.Printf("User %d was created", u.Id)
})

// Subscribe for updated users
bus.SubVal(b, Updated, func(ctx context.Context, u *User) {
	log.Printf("User %d was updated", u.Id)
})

// Publish to Created topic. This will always do 1 allocation due to the pointer.
bus.SubVal(b, Created, &User{
	Id:   123,
	Name: "John Doe"
})

Documentation

Overview

Example (Subscribers)
subs := newSubscribers(64)

subs.add(1)
subs.add(1)
subs.add(1)

fmt.Println(subs.count(1))
Output:
mjau

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Pub

func Pub(b *Bus, topic Topic)

Publish an event to a bus.

func PubVal added in v0.3.0

func PubVal[T any](b *Bus, topic Topic, v *T)

Publish an event to a bus with a value.

func Sub

func Sub(b *Bus, topic Topic, cb func(context.Context))

func SubVal added in v0.3.0

func SubVal[T any](b *Bus, topic Topic, cb func(context.Context, *T))

Subscribe to a topic with value. The provided callback will be called whenever a matching event arrives.

func Unsub added in v0.3.0

func Unsub(b *Bus, topic Topic, cb func(context.Context))

func UnsubVal added in v0.3.0

func UnsubVal[T any](b *Bus, topic Topic, cb func(context.Context, *T))

Types

type Bus

type Bus struct {
	// contains filtered or unexported fields
}

Event bus

func NewBus

func NewBus(ctx context.Context, capacity int) *Bus

Creates a new bus with a worker.

func (*Bus) Close

func (b *Bus) Close()

func (*Bus) Empty

func (b *Bus) Empty() bool

func (*Bus) Full

func (b *Bus) Full() bool

func (*Bus) MaxSize

func (b *Bus) MaxSize() int

func (*Bus) Size

func (b *Bus) Size() int

type Topic

type Topic uint64

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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