goemitter/example/main.go

66 lines
1.1 KiB
Go
Raw Permalink Normal View History

2023-11-29 23:48:57 +08:00
package main
import (
"fmt"
2024-09-19 16:41:07 +08:00
"log"
"runtime/debug"
"time"
2023-11-29 23:48:57 +08:00
emitter "git.pyer.club/kingecg/goemitter"
)
type St struct {
Name string
}
func (s *St) Print(data ...interface{}) {
fmt.Println(s.Name)
fmt.Println(data...)
}
2024-11-16 16:12:20 +08:00
type A struct {
Name string
}
func (a *A) Exec(data ...interface{}) {
fmt.Println(a.Name, data)
}
2023-11-29 23:48:57 +08:00
func main() {
s := &St{Name: "testeer"}
em := emitter.NewEmitter()
2024-11-16 16:12:20 +08:00
emh := em.On("test", func(data ...interface{}) {
fmt.Println("should be canceled next")
2023-11-29 23:48:57 +08:00
fmt.Println(data...)
2024-11-16 16:12:20 +08:00
2023-11-29 23:48:57 +08:00
})
em.On("test", s.Print)
em.Once("test", func(data ...interface{}) {
s := fmt.Sprint(data...)
fmt.Println(interface{}("Once"), s)
})
2024-11-16 16:12:20 +08:00
func() {
em.On("test", func(data ...interface{}) {
fmt.Println("函数内匿名函数被调用")
})
}()
func() {
a := &A{Name: "ATEST"}
em.On("test", a.Exec)
}()
2023-11-29 23:48:57 +08:00
em.EmitSync("test", "hello", "world")
2024-11-16 16:12:20 +08:00
emh.Remove()
2023-11-29 23:48:57 +08:00
em.Emit("test", "hello", "world2")
2024-11-16 16:12:20 +08:00
2024-09-19 16:41:07 +08:00
defer func() {
if r := recover(); r != nil {
log.Println("Recovered in main:", r)
// 打印当前所有 goroutine 的堆栈信息
log.Println(string(debug.Stack()))
}
}()
2024-11-16 16:12:20 +08:00
time.Sleep(10 * time.Second)
2023-11-29 23:48:57 +08:00
}