共计 1222 个字符,预计需要花费 4 分钟才能阅读完成。
go-eventbus 事件总线
地址: github.com/lockp111/go-eventbus
参考 go-observable, 然而那个代码有问题, 会因为 map 同时读写呈现 crash, 我修复之后提交给作者也始终不理我, 于是就本人 fork 一份自用, 起初感觉反射调用的损耗还是比拟大的, 而且应用 func 如果不留神, 有可能呈现两个雷同的 func, 于是改成 interface, Benchmark 显示晋升十分大
Usage
go get -u github.com/lockp111/go-eventbus
New()
Create a new bus struct reference
bus := eventbus.New()
On(topic string, e …Event)
Subscribe event
type ready struct{
}
func (e ready) Dispatch(msg interface{}){fmt.Println("I am ready!")
}
bus.On("ready", &ready{})
You can also subscribe multiple events for example:
type run struct{
}
func (e run) Dispatch(msg interface{}){fmt.Println("I am run!")
}
bus.On("ready", &ready{}, &ready{}).On("run", &run{})
Off(topic string, e …Event)
Unsubscribe event
e := &ready{}
bus.On("ready", e)
bus.Off("ready", e)
You can also unsubscribe multiple events for example:
e1 := &ready{}
e2 := &ready{}
bus.On("ready", e1, e2)
bus.Off("ready", e1, e2)
You can unsubscribe all events for example:
bus.On("ready", &ready{}, &ready{})
bus.Off("ready")
You can unsubscribe all topics for example:
bus.On("ready", &ready{}, &ready{})
bus.On("run", &run{})
bus.Off(ALL)
Trigger(topic string, msg …interface{})
Dispatch events
bus.Trigger("ready")
You can also dispatch multiple events for example:
bus.Trigger("ready", &struct{"1"}, &struct{"2"})
You can also dispatch all events for example:
bus.Trigger(ALL, &struct{"1"})
正文完