Skip to content

This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event.

License

Notifications You must be signed in to change notification settings

leonsteinhaeuser/observer

Folders and files

NameName
Last commit message
Last commit date
Nov 30, 2022
Nov 14, 2022
Apr 10, 2022
Oct 26, 2022
Apr 9, 2022
Oct 29, 2022
Oct 29, 2022
Oct 26, 2022
Nov 14, 2022
Nov 14, 2022

Repository files navigation

observer

tests codecov release date commits since release open: bugs open: feature requests issues closed license

This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event.

Differences between v1 and v2

The v2 release contains breaking changes. The most important ones are:

  • The Observable interface does not provide a Clients() int64 method anymore.
  • The constructor NewObserver() has been removed. Instead, use new(observer.Observer[T]).
  • The Observer has become a NotifyTimeout that can be used to set a timeout for the NotifyAll method. The default value is 5 * time.Second.

Usage

go get github.com/leonsteinhaeuser/observer/v2

Example

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.