Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/goxiaoy/go-eventbus
simple strong typed event bus from golang generics
https://github.com/goxiaoy/go-eventbus
eventbus generic go strongly-typed
Last synced: 3 months ago
JSON representation
simple strong typed event bus from golang generics
- Host: GitHub
- URL: https://github.com/goxiaoy/go-eventbus
- Owner: goxiaoy
- License: mit
- Created: 2022-03-31T04:49:09.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-04-01T07:44:01.000Z (almost 3 years ago)
- Last Synced: 2024-06-21T06:36:27.479Z (7 months ago)
- Topics: eventbus, generic, go, strongly-typed
- Language: Go
- Homepage:
- Size: 12.7 KB
- Stars: 8
- Watchers: 2
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-eventbus
simple strong typed event bus from golang generics.you can use it as a local eventbus or a mediator for [CQRS](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation)
- [x] Publish, Subscribe/SubscribeOnce/Subscribe (with type assertion)
- [x] Dispatch, AddProcessor## Install
```
go get github.com/goxiaoy/go-eventbus
```## Usage
### create a eventbus or skip to use Default one
```go
bus := eventbus.New()
```### Publish and Subscribe
```go
type TestEvent1 struct {
}func main() {
ctx := context.Background()
//Subscribe
dispose, err := eventbus.Subscribe[*TestEvent1](bus)(func(ctx context.Context, event *TestEvent1) error {
fmt.Print("do TestEvent1")
return nil
})
if err != nil {
panic(err)
}
//Publish
err = eventbus.Publish[*TestEvent1](bus)(ctx, &TestEvent1{})
if err != nil {
panic(err)
}
//UnSubscribe
err = dispose.Dispose()
if err != nil {
panic(err)
}}
```
Subscribe to any```go
//You can also subscribe to any
dispose, err = eventbus.Subscribe[interface{}](bus)(func(ctx context.Context, event interface{}) error {
fmt.Println("do any")
return nil
})
```Subscribe once
```go
dispose, err = eventbus.SubscribeOnce[interface{}](bus)(func(ctx context.Context, event interface{}) error {
fmt.Println("do any")
return nil
})
```### Dispatch and Process
```go
//Processor
dispose, err = eventbus.AddProcessor[*TestEvent1, *TestResult1](bus)(func(ctx context.Context, event *TestEvent1) (*TestResult1, error) {
fmt.Println("return result")
return &TestResult1{}, err
})
//Dispatch
result, err := eventbus.Dispatch[*TestEvent1, *TestResult1](bus)(ctx, &TestEvent1{})
if err != nil {
panic(err)
}
```## Limitation
- This eventbus is designed as `O(n)` complexity.
- Do not support Dispatch/Process Result interface type