123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- package flowutil
- import "sync"
- type EventPump struct {
- eventsObservers map[string]map[interface{}][]EventCallback
- eventsObserversLock *sync.Mutex
- }
- type EventCallback func(event string, eventSource interface{})
- func NewEventPump() *EventPump {
- return &EventPump{make(map[string]map[interface{}][]EventCallback), &sync.Mutex{}}
- }
- func (ep *EventPump) AddObserver(event string, eventSource interface{}, callback EventCallback) {
-
- if callback == nil {
- return
- }
- ep.eventsObserversLock.Lock()
- defer ep.eventsObserversLock.Unlock()
- sources, ok := ep.eventsObservers[event]
- if !ok {
- sources = make(map[interface{}][]EventCallback)
- ep.eventsObservers[event] = sources
- }
- callbacks, ok := sources[eventSource]
- if !ok {
- callbacks = []EventCallback{callback}
- sources[eventSource] = callbacks
- } else {
- sources[eventSource] = append(callbacks, callback)
- }
- }
- func (ep *EventPump) PostEvent(event string, eventSource interface{}) {
- if event == "" || eventSource == nil {
- panic("Posting an event requires the event and its source")
- }
- postEvent := func(event string, eventSource interface{}) {
- ep.eventsObserversLock.Lock()
- sources, ok := ep.eventsObservers[event]
- if ok {
- origsources := sources
- sources = make(map[interface{}][]EventCallback)
- for source, callbacks := range origsources {
- sources[source] = callbacks
- }
- }
- ep.eventsObserversLock.Unlock()
- if ok {
- for source, callbacks := range sources {
- if source == eventSource || source == nil {
- for _, callback := range callbacks {
- callback(event, eventSource)
- }
- }
- }
- }
- }
- postEvent(event, eventSource)
- postEvent("", eventSource)
- }
- func (ep *EventPump) RemoveObservers(event string, eventSource interface{}) {
- ep.eventsObserversLock.Lock()
- defer ep.eventsObserversLock.Unlock()
-
- if event == "" && eventSource == nil {
- ep.eventsObservers = make(map[string]map[interface{}][]EventCallback)
- } else if eventSource == nil {
- delete(ep.eventsObservers, event)
- } else if event == "" {
- for _, sources := range ep.eventsObservers {
- delete(sources, eventSource)
- }
- } else {
- if sources, ok := ep.eventsObservers[event]; ok {
- delete(sources, eventSource)
- }
- }
- }
|