summaryrefslogtreecommitdiff
path: root/pkg/events/general.go
blob: 5cf13e1070745bcb67f397096699467888b4ec46 (plain)
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
package events

import (
	"sync"
)

const UnknownEventType string = "Unknown event type"

// HandlerImpl helps to broadcast events to multiple listeners.
type HandlerImpl struct {
	listeners    []Listener
	sync.RWMutex // all receivers should be pointers
}

func NewEventsHandler() Handler {
	return &HandlerImpl{listeners: make([]Listener, 0, 2)}
}

// NumListeners returns number of event listeners.
func (eb *HandlerImpl) NumListeners() int {
	eb.Lock()
	defer eb.Unlock()
	return len(eb.listeners)
}

// AddListener registers new event listener.
func (eb *HandlerImpl) AddListener(listener Listener) {
	eb.Lock()
	defer eb.Unlock()
	eb.listeners = append(eb.listeners, listener)
}

// Push broadcast events across all event listeners.
func (eb *HandlerImpl) Push(e interface{}) {
	// ReadLock here because we are not changing listeners
	eb.RLock()
	defer eb.RUnlock()
	for k := range eb.listeners {
		eb.listeners[k](e)
	}
}