Package EventBus is the little and lightweight eventbus for GoLang.
Make sure that Go is installed on your computer. Type the following command in your terminal:
go get github.com/asaskevich/EventBus
After it the package is ready to use.
Add following line in your *.go file:
import "github.com/asaskevich/EventBus"
If you unhappy to use long EventBus, you can do something like this:
import ( evbus "github.com/asaskevich/EventBus" )
func calculator(a int, b int) { fmt.Printf("%d\n", a + b) } func main() { bus := EventBus.New(); bus.Subscribe("main:calculator", calculator); bus.Publish("main:calculator", 20, 40); bus.Unsubscribe("main:calculator"); }
New returns new EventBus with empty handlers.
bus := EventBus.New();
Subscribe to a channel.
func Handler() { ... } ... bus.Subscribe("channel:handler", Handler)
Subscribe to a channel once. Handler will be removed after executing.
func HelloWorld() { ... } ... bus.SubscribeOnce("channel:handler", HelloWorld)
Remove callback defined for a channel.
bus.Unsubscribe("channel:handler");
Execute callback defined for a channel. Any addional argument will be tranfered to the callback.
func Handler(str string) { ... } ... bus.Subscribe("channel:handler", Handler) ... bus.Publish("channel:handler", "Hello, World!");
If you do have a contribution for the package feel free to put up a Pull Request or open Issue.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
It depends on the intended usage. If it is the idea that several goroutines can add listeners and publish events the you have to protect the map.
By synchronous I mean that the caller of publish have to wait for all registered subscribers to complete. That can be a valid use case but maybe not always what you want.
package main
import ( "EventBus" "time" "fmt")
func A() { time.Sleep(1000 * time.Millisecond) fmt.Printf("A done\n")}
func B() { time.Sleep(1500 * time.Millisecond) fmt.Printf("B done\n")}
func C() { time.Sleep(500 * time.Millisecond) fmt.Printf("C done\n")}
func main() { bus := EventBus.New(); bus.Subscribe("A", A); bus.Subscribe("B", B); bus.Subscribe("C", C);
go func() { bus.Publish("B"); bus.Publish("B"); bus.Publish("B"); }()
go func() { bus.Publish("C"); bus.Publish("C"); bus.Publish("C"); }()
bus.Publish("A"); bus.Publish("A"); bus.Publish("A");
time.Sleep(9000 * time.Millisecond)}A doneA doneA doneB doneB doneB doneC doneC doneC done