A simple library to make the observer pattern simpler to implement.
Note
This repository moved from xmidt-org/eventor.
The Go module path is now github.com/rdkcentral/eventor. To migrate, change
imports of github.com/xmidt-org/eventor to github.com/rdkcentral/eventor.
eventor provides Eventor[T], a generic, concurrency-safe set of listeners
that you can add to, cancel from, and dispatch events to. The zero value is
ready to use.
go get github.com/rdkcentral/eventorpackage main
import (
"fmt"
"github.com/rdkcentral/eventor"
)
// A listener can be any type; a func is the most common choice.
type Listener func(msg string)
func main() {
var events eventor.Eventor[Listener]
cancel := events.Add(func(msg string) {
fmt.Println("got:", msg)
})
defer cancel()
// Dispatch an event to every listener.
events.Visit(func(l Listener) {
l("hello")
})
}Add returns a cancel func that removes the listener. It is idempotent, so
calling it more than once is safe.
Visit takes a snapshot of the listeners and then calls each one without
holding any lock. This means:
- Listeners may call
Add, a cancel func, orVisitfrom inside the callback, so a one-shot listener can cancel itself. - A listener added during a visit is first called on the next visit.
- A listener canceled during a visit may still be called once in that visit if it had not been reached yet.
- A slow listener does not block
Addor cancel on other goroutines, but it does delay the remaining listeners in that visit.
This project and everyone participating in it are governed by the XMiDT Code Of Conduct. By participating, you agree to this Code.
Refer to CONTRIBUTING.md.