generated from shahariaazam/go-pkg
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgevli.go
63 lines (54 loc) · 1.52 KB
/
gevli.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Package gevli provides simple implementation of event listener
package gevli
import (
"sync"
)
// Listener is a function that will be called when an event is emitted.
type Listener func(Event)
// Event is a struct that represents an event.
type Event struct {
Type string
Data interface{}
}
// EventEmitter is a struct that manages event listeners and emits events.
type EventEmitter struct {
mu sync.Mutex
listeners map[string][]Listener
}
// NewEventEmitter creates a new EventEmitter.
func NewEventEmitter() *EventEmitter {
return &EventEmitter{
listeners: make(map[string][]Listener),
}
}
// AddListener adds a new listener for a specific event type.
func (e *EventEmitter) AddListener(eventType string, listener Listener) {
e.mu.Lock()
defer e.mu.Unlock()
e.listeners[eventType] = append(e.listeners[eventType], listener)
}
// Emit emits an event to all registered listeners asynchronously.
func (e *EventEmitter) Emit(eventType string, data interface{}) {
e.mu.Lock()
defer e.mu.Unlock()
e.processListener(eventType, data, false)
}
// EmitSync emits an event to all registered listeners synchronously.
func (e *EventEmitter) EmitSync(eventType string, data interface{}) {
e.mu.Lock()
defer e.mu.Unlock()
e.processListener(eventType, data, true)
}
func (e *EventEmitter) processListener(eventType string, data interface{}, sync bool) {
event := Event{
Type: eventType,
Data: data,
}
for _, listener := range e.listeners[eventType] {
if sync {
listener(event)
} else {
go listener(event)
}
}
}