This repository contains a simple, in-process event dispatcher to be used to decouple internal modules. It provides a generic way to define events, publish and subscribe to them.
// Various event types
const EventA = 0x01
// Event type for testing purposes
type myEvent struct{
Data string
}
// Type returns the event type
func (ev myEvent) Type() uint32 {
return EventA
}
For convenience, this package provides a default global dispatcher that can be used with On()
and Emit()
package-level functions.
// Subcribe to event A, and automatically unsubscribe at the end
defer event.On(func(e Event) {
println("(consumer)", e.Data)
})()
// Publish few events
event.Emit(newEventA("event 1"))
event.Emit(newEventA("event 2"))
event.Emit(newEventA("event 3"))
When publishing events, you can create a Dispatcher
which is then used as a target of generic event.Publish[T]()
and event.Subscribe[T]()
functions to publish and subscribe to various event types respectively.
bus := event.NewDispatcher()
// Subcribe to event A, and automatically unsubscribe at the end
defer event.Subscribe(bus, func(e Event) {
println("(consumer 1)", e.Data)
})()
// Subcribe to event A, and automatically unsubscribe at the end
defer event.Subscribe(bus, func(e Event) {
println("(consumer 2)", e.Data)
})()
// Publish few events
event.Publish(bus, newEventA("event 1"))
event.Publish(bus, newEventA("event 2"))
event.Publish(bus, newEventA("event 3"))
It should output something along these lines, where order is not guaranteed given that both subscribers are processing messages asyncrhonously.
(consumer 2) event 1
(consumer 2) event 2
(consumer 2) event 3
(consumer 1) event 1
(consumer 1) event 2
(consumer 1) event 3
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
BenchmarkEvent/1x1-24 38709926 31.94 ns/op 30.89 million/s 1 B/op 0 allocs/op
BenchmarkEvent/1x10-24 8107938 133.7 ns/op 74.76 million/s 45 B/op 0 allocs/op
BenchmarkEvent/1x100-24 774168 1341 ns/op 72.65 million/s 373 B/op 0 allocs/op
BenchmarkEvent/10x1-24 5755402 301.1 ns/op 32.98 million/s 7 B/op 0 allocs/op
BenchmarkEvent/10x10-24 750022 1503 ns/op 64.47 million/s 438 B/op 0 allocs/op
BenchmarkEvent/10x100-24 69363 14878 ns/op 67.11 million/s 3543 B/op 0 allocs/op