mitto provides a simple API around application event handling
mitto
(Latin verb meaning "to send") implements a simple way to manage a set of listeners and
dispatch application events to those listeners. mitto
is primarily intended for code which
sends events to clients, where clients supply one or more listeners.
The easiest way to use mitto
is to include it in a type that manages events and listeners:
import github.com/xmidt-org/mitto
type Event {
// stuff
}
type MyListener interface {
OnEvent(Event)
}
type MyService struct {
// could also use mitto.Set if concurrency is
// managed by MyService or some other means.
listeners mitto.SyncSet[Event]
}
func (s *MyService) Add(l ...MyListener) {
mitto.Add(&s.listeners, l...)
}
func (s *MyService) Remove(l ...MyListener) {
mitto.Remove(&s.listeners, l...)
}
func (s *MyService) DoSomething() {
// time to send an event:
s.listeners.Send(Event{
// stuff
})
}
mitto
provides AsListener
to convert other common types into listeners.
f := func(event Event) { /* ... */ }
ch := make(chan Event, 10)
s.listeners.Add(
mitto.AsListener[Event](f),
mitto.AsListener[Event](ch),
)
A client is responsible for ensuring that a channel is properly managed to reduce or avoid blocking. In addition, a client must remove the channel listener before closing the channel, otherwise Send
may panic.
ch := make(chan Event, 10)
l := AsListener[Event](ch)
s.listeners.Add(l)
// remove the listener BEFORE closing the channel
s.listeners.Remove(l)
close(ch)
AsListener
can also be used to adapt a different listener interface or type.
type DifferentListener interface {
OnStartEvent(Event)
}
func (s *MyService) AddDifferentListener(l DifferentListener) {
s.listeners.Add(
mitto.AsListener[Event](
l.OnStartEvent,
),
)
}
This project and everyone participating in it are governed by the XMiDT Code Of Conduct. By participating, you agree to this Code.
go get github.com/xmidt-org/mitto@latest
Refer to CONTRIBUTING.md.