event

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2024 License: MIT Imports: 3 Imported by: 0

README

Event

Usage

package main

import (
	"fmt"
	"time"

	"github.com/go-kratos-ecosystem/components/v2/event"
	"github.com/go-kratos-ecosystem/components/v2/feature"
)

type testListener struct {
	feature.AsyncFeature  // async feature
}

func (l *testListener) Listen() []event.Event {
	return []event.Event{
		"test",
		"test2",
	}
}

func (l *testListener) Handle(e event.Event, data interface{}) {
	if s, ok := data.(string); ok {
		fmt.Println("event:", e, "data:", s)
	} else {
		panic("invalid data")
	}
}

type test2Listener struct{}

func (l *test2Listener) Listen() []event.Event {
	return []event.Event{
		"test",
	}
}

func (l *test2Listener) Handle(event event.Event, data interface{}) {
	fmt.Println("event:", event, "data:", data)
}

func main() {
	d := event.NewDispatcher(event.WithRecovery(func(err interface{}, listener event.Listener, event event.Event, data interface{}) { //nolint:lll
		fmt.Println("err:", err, "listener:", listener, "event:", event, "data:", data)
	}))

	d.AddListener(new(testListener), new(test2Listener))

	d.Dispatch("test", "test data")
	d.Dispatch("test2", "test2 data")
	d.Dispatch("test3", "test3 data")

	time.Sleep(time.Second)
}

Output:

event: test data: test data
event: test2 data: test2 data
event: test data: test data

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultRecovery = func(err interface{}, event Event, data interface{}) {
	log.Errorf("[Event] handler panic event: %s, data: %v, err: %v", event, data, err)
}

Functions

This section is empty.

Types

type Dispatcher

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

func NewDispatcher

func NewDispatcher(opts ...Option) *Dispatcher

func (*Dispatcher) AddListener

func (d *Dispatcher) AddListener(listener ...Listener)

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(event Event, data interface{})

type Event

type Event string

type Listener

type Listener interface {
	Listen() []Event
	Handle(event Event, data interface{})
}

type Option

type Option func(*Dispatcher)

func WithRecovery

func WithRecovery(handler func(err interface{}, listener Listener, event Event, data interface{})) Option

Jump to

Keyboard shortcuts

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