generated from atomicgo/template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9ade776
commit 3c3937b
Showing
2 changed files
with
84 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,53 @@ | ||
package event | ||
|
||
import "sync" | ||
|
||
// Event represents an event system that can handle multiple listeners. | ||
type Event[T any] struct { | ||
listeners []chan T | ||
mu sync.Mutex | ||
} | ||
|
||
func New[T any]() *Event[T] { | ||
return &Event[T]{ | ||
listeners: []chan T{}, | ||
} | ||
} | ||
|
||
// Trigger triggers the event and notifies all listeners. | ||
func (e *Event[T]) Trigger(value T) { | ||
e.mu.Lock() | ||
defer e.mu.Unlock() | ||
|
||
for _, listener := range e.listeners { | ||
go func(l chan T) { | ||
l <- value | ||
}(listener) | ||
} | ||
} | ||
|
||
// Listen gets called when the event is triggered. | ||
func (e *Event[T]) Listen(f func(T)) { | ||
ch := make(chan T) | ||
|
||
e.mu.Lock() | ||
e.listeners = append(e.listeners, ch) | ||
e.mu.Unlock() | ||
|
||
go func() { | ||
for v := range ch { | ||
f(v) | ||
} | ||
}() | ||
} | ||
|
||
func (e *Event[T]) Close() { | ||
e.mu.Lock() | ||
defer e.mu.Unlock() | ||
|
||
for _, listener := range e.listeners { | ||
close(listener) | ||
} | ||
|
||
e.listeners = nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters