Documentation ¶
Overview ¶
Package eventlib provides a generic event emitter implementation for Go applications.
The package implements a type-safe event emitter pattern using Go generics, allowing for strongly-typed event handling with support for concurrent operations. It provides a simple pub/sub (publish/subscribe) mechanism that can be used to implement event-driven architectures in Go applications.
Basic usage:
// Create a new emitter for string events with a context and buffer size emitter := eventlib.NewEmitter[string](context.Background(), 10) // Subscribe to events emitter.Subscribe( func(data string) error { fmt.Println("Received:", data) return nil }, func(err error) { fmt.Println("Error:", err) }, ) // Emit events emitter.Emit("Hello, World!") // Clean up when done defer emitter.End()
Features:
- Generic type support for type-safe event handling
- Buffered or unbuffered event channels
- Concurrent-safe operation with mutex protection
- Context-based cancellation
- Error handling support
- Panic recovery in event handlers
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Emitter ¶
type Emitter[T any] struct { // contains filtered or unexported fields }
Emitter is a generic event emitter that supports type-safe event handling. It provides concurrent-safe operations for emitting and handling events of type T.
func NewEmitter ¶
NewEmitter creates a new event emitter with the specified context and channel buffer size. If size is 0 or negative, an unbuffered channel is created. The returned emitter must be cleaned up by calling End() when no longer needed.
func (*Emitter[T]) Emit ¶
func (e *Emitter[T]) Emit(data T)
Emit sends a new event to all subscribed handlers. If the emitter's context is cancelled or the channel is full, the event will be dropped.
func (*Emitter[T]) GetEmitter ¶
func (e *Emitter[T]) GetEmitter() func(T)
GetEmitter returns a function that can be used to emit events. This is useful when you want to pass the emit capability without exposing the entire Emitter interface.
func (*Emitter[T]) Subscribe ¶
Subscribe adds a new event handler to the emitter. The onEvent function is called for each emitted event. The onError function is called when an error occurs during event handling. If onEvent is nil, the subscription is ignored. Multiple handlers can be subscribed to the same emitter.