commit 5f03f88d730c4b1c298c4c3eeceeba8023f056ff Author: Shelikhoo xiaokangwang@outlook.com Date: Fri Nov 26 16:00:30 2021 +0000
Add Event Bus Implementation
This event bus implementation favours simplicity over efficiency and is not suitable for frequent addition and removal of listeners. --- common/event/bus.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+)
diff --git a/common/event/bus.go b/common/event/bus.go new file mode 100644 index 0000000..7e45779 --- /dev/null +++ b/common/event/bus.go @@ -0,0 +1,39 @@ +package event + +import "sync" + +func NewSnowflakeEventDispatcher() SnowflakeEventDispatcher { + return &eventBus{lock: &sync.Mutex{}} +} + +type eventBus struct { + lock *sync.Mutex + listeners []SnowflakeEventReceiver +} + +func (e *eventBus) OnNewSnowflakeEvent(event SnowflakeEvent) { + e.lock.Lock() + defer e.lock.Unlock() + for _, v := range e.listeners { + v.OnNewSnowflakeEvent(event) + } +} + +func (e *eventBus) AddSnowflakeEventListener(receiver SnowflakeEventReceiver) { + e.lock.Lock() + defer e.lock.Unlock() + e.listeners = append(e.listeners, receiver) +} + +func (e *eventBus) RemoveSnowflakeEventListener(receiver SnowflakeEventReceiver) { + e.lock.Lock() + defer e.lock.Unlock() + var newListeners []SnowflakeEventReceiver + for _, v := range e.listeners { + if v != receiver { + newListeners = append(newListeners, v) + } + } + e.listeners = newListeners + return +}
tor-commits@lists.torproject.org