go-eventbus事件总线

go-eventbus事件总线

地址: github.com/lockp111/go-eventbusgit

参考go-observable, 可是那个代码有问题, 会由于map同时读写出现crash, 我修复以后提交给做者也一直不理我, 因而就本身fork一份自用, 后来以为反射调用的损耗仍是比较大的, 并且使用func若是不注意, 有可能出现两个相同的func, 因而改为interface, Benchmark显示提高很是大github

Usage

go get -u github.com/lockp111/go-eventbus

New()

Create a new bus struct referencesegmentfault

bus := eventbus.New()

On(topic string, e ...Event)

Subscribe eventurl

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:spa

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 eventcode

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:ip

bus.On("ready", &ready{}, &ready{})
bus.Off("ready")

You can unsubscribe all topics for example:get

bus.On("ready", &ready{}, &ready{})
bus.On("run", &run{})
bus.Off(ALL)

Trigger(topic string, msg ...interface{})

Dispatch eventsstring

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"})
相关文章
相关标签/搜索