go-eventbus事件总线

harman · · 2213 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

# go-eventbus事件总线 地址: [github.com/lockp111/go-eventbus](https://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 ```go bus := eventbus.New() ``` ### On(topic string, e ...Event) Subscribe event ```go 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: ```go 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 ```go e := &ready{} bus.On("ready", e) bus.Off("ready", e) ``` You can also unsubscribe multiple events for example: ```go e1 := &ready{} e2 := &ready{} bus.On("ready", e1, e2) bus.Off("ready", e1, e2) ``` You can unsubscribe all events for example: ```go bus.On("ready", &ready{}, &ready{}) bus.Off("ready") ``` You can unsubscribe all topics for example: ```go bus.On("ready", &ready{}, &ready{}) bus.On("run", &run{}) bus.Off(ALL) ``` ### Trigger(topic string, msg ...interface{}) Dispatch events ```go bus.Trigger("ready") ``` You can also dispatch multiple events for example: ```go bus.Trigger("ready", &struct{"1"}, &struct{"2"}) ``` You can also dispatch all events for example: ```go bus.Trigger(ALL, &struct{"1"}) ```

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2213 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传