Refactors the event emitter system from string-based messages to a type-safe generic implementation using typed events. Consolidates separate tracker packages into a unified plugins architecture. Changes: - Replace Emitter with BaseEmitter[E comparable] using generics - Add Event type with StartEvent, StepEvent, and StopEvent constants - Create Listener[E] interface with BaseListener implementation - Consolidate explanation, performance, and statistics trackers into internal/plugins package - Simplify main CLI by using plugin constructors instead of manual event subscription - Add Items() iterator method to Set for idiomatic range loops
40 lines
796 B
Go
40 lines
796 B
Go
package emitter
|
|
|
|
import "git.maximhutz.com/max/lambda/pkg/set"
|
|
|
|
type Emitter[E comparable] interface {
|
|
On(string, func()) Listener[E]
|
|
Off(Listener[E])
|
|
Emit(E)
|
|
}
|
|
|
|
type BaseEmitter[E comparable] struct {
|
|
listeners map[E]*set.Set[Listener[E]]
|
|
}
|
|
|
|
func (e *BaseEmitter[E]) On(kind E, fn func()) Listener[E] {
|
|
if e.listeners[kind] == nil {
|
|
e.listeners[kind] = set.New[Listener[E]]()
|
|
}
|
|
|
|
listener := &BaseListener[E]{kind, fn}
|
|
e.listeners[kind].Add(listener)
|
|
return listener
|
|
}
|
|
|
|
func (e *BaseEmitter[E]) Emit(event E) {
|
|
if e.listeners[event] == nil {
|
|
e.listeners[event] = set.New[Listener[E]]()
|
|
}
|
|
|
|
for listener := range e.listeners[event].Items() {
|
|
listener.Run()
|
|
}
|
|
}
|
|
|
|
func New[E comparable]() *BaseEmitter[E] {
|
|
return &BaseEmitter[E]{
|
|
listeners: map[E]*set.Set[Listener[E]]{},
|
|
}
|
|
}
|