events

package
v12.116.0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: Apache-2.0 Imports: 3 Imported by: 8

Documentation

Overview

Package events provides methods and structs for creating event-driven systems

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNilDispatcher = fmt.Errorf("Dispatcher is nil")
	ErrEmptyType     = fmt.Errorf("Event type is empty")
	ErrNilHandler    = fmt.Errorf("Handler must not be nil")
)

Functions

This section is empty.

Types

type Dispatcher

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

Dispatcher is event dispatcher

func NewDispatcher

func NewDispatcher() *Dispatcher

NewDispatcher creates new event dispatcher instance

Example
d := NewDispatcher()

d.AddHandler("myEvent", testHandler)

d.Dispatch("myEvent", "Hello!")
Output:

func (*Dispatcher) AddHandler

func (d *Dispatcher) AddHandler(typ string, handler Handler) error

AddHandler registers handler for events with given event type

Example
d := NewDispatcher()

d.AddHandler("myEvent", testHandler)
d.AddHandler("unknownEvent", testHandler)

err := d.Dispatch("myEvent", "Hello!")

fmt.Println(err) // nil
Output:

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(typ string, payload any) error

Dispatch dispatches event with given type and payload

Example
d := NewDispatcher()

d.AddHandler("myEvent", testHandler)

err := d.Dispatch("myEvent", "Hello!")

fmt.Println(err) // nil
Output:

func (*Dispatcher) DispatchAndWait

func (d *Dispatcher) DispatchAndWait(typ string, payload any) error

DispatchAndWait dispatches event with given type and payload and waits until all handlers will be executed

Example
d := NewDispatcher()

d.AddHandler("myEvent", testHandler)

err := d.DispatchAndWait("myEvent", "Hello!")

fmt.Println(err) // nil
Output:

func (*Dispatcher) HasHandler

func (d *Dispatcher) HasHandler(typ string, handler Handler) bool

HasHandler returns true if given handler is registered for given event type

Example
d := NewDispatcher()

d.AddHandler("myEvent", testHandler)

fmt.Println("myEvent:", d.HasHandler("myEvent", testHandler))
fmt.Println("unknownEvent:", d.HasHandler("unknownEvent", testHandler))
Output:

myEvent: true
unknownEvent: false

func (*Dispatcher) RemoveHandler

func (d *Dispatcher) RemoveHandler(typ string, handler Handler) error

RemoveHandler removes handler for given event type

Example
d := NewDispatcher()

d.AddHandler("myEvent", testHandler)
d.RemoveHandler("myEvent", testHandler)

err := d.Dispatch("myEvent", "Hello!")

fmt.Println(err) // not nil
Output:

type Handler

type Handler func(payload any)

Handler is a function that handles an event

type Handlers

type Handlers []Handler

Handlers is a slice with handlers

Jump to

Keyboard shortcuts

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