This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event.
The v2 release contains breaking changes. The most important ones are:
- The
Observable
interface does not provide aClients() int64
method anymore. - The constructor
NewObserver()
has been removed. Instead, usenew(observer.Observer[T])
. - The
Observer
has become aNotifyTimeout
that can be used to set a timeout for theNotifyAll
method. The default value is5 * time.Second
.
go get github.com/leonsteinhaeuser/observer/v2
package main
import (
"fmt"
"github.com/leonsteinhaeuser/observer/v2"
)
type Event struct {
ID int
Message string
}
var (
obsrv *observer.Observer[Event] = new(observer.Observer[Event])
)
func main() {
rspCh, cancelFunc := obsrv.Subscribe()
defer cancelFunc()
go func() {
for {
fmt.Printf("Received event: %v\n", <-rspCh)
}
}()
fmt.Println("Registered Clients: ", obsrv.Clients())
obsrv.NotifyAll(Event{
ID: i,
Message: "Hello World",
})
}
If you would like to see a more detailed example, please take a look at the observer example.