feat(eventbus): enhance event handling with error propagation and global bus management

This commit is contained in:
mlogclub
2026-04-21 11:50:43 +08:00
parent 964b2ed6ce
commit df13d5ced5
4 changed files with 267 additions and 21 deletions
+39
View File
@@ -1,6 +1,7 @@
package eventbus
import (
"context"
"reflect"
"sync"
)
@@ -10,6 +11,24 @@ var (
buss = make(map[reflect.Type]any)
)
// Register initializes the global bus for T. If the bus already exists, the
// existing instance is returned and later options are ignored.
func Register[T any](opts ...Option[T]) *Bus[T] {
key := eventTypeOf[T]()
mu.Lock()
defer mu.Unlock()
if bus, ok := buss[key]; ok {
return bus.(*Bus[T])
}
created := New[T](opts...)
buss[key] = created
return created
}
// Get returns the global bus for T, creating it with default options if needed.
func Get[T any]() *Bus[T] {
key := eventTypeOf[T]()
@@ -39,3 +58,23 @@ func eventTypeOf[T any]() reflect.Type {
}
return typ
}
// Subscribe registers a handler on the global bus for T.
func Subscribe[T any](h Handler[T]) (uint64, func()) {
return Get[T]().Subscribe(h)
}
// SubscribeOnce registers a handler that runs at most once on the global bus for T.
func SubscribeOnce[T any](h Handler[T]) (uint64, func()) {
return Get[T]().SubscribeOnce(h)
}
// Publish synchronously publishes event to the global bus for T.
func Publish[T any](ctx context.Context, event T) error {
return Get[T]().Publish(ctx, event)
}
// PublishAsync asynchronously publishes event to the global bus for T.
func PublishAsync[T any](ctx context.Context, event T) {
Get[T]().PublishAsync(ctx, event)
}