bus.go 861 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package event
  2. import "sync"
  3. func NewSnowflakeEventDispatcher() SnowflakeEventDispatcher {
  4. return &eventBus{lock: &sync.Mutex{}}
  5. }
  6. type eventBus struct {
  7. lock *sync.Mutex
  8. listeners []SnowflakeEventReceiver
  9. }
  10. func (e *eventBus) OnNewSnowflakeEvent(event SnowflakeEvent) {
  11. e.lock.Lock()
  12. defer e.lock.Unlock()
  13. for _, v := range e.listeners {
  14. v.OnNewSnowflakeEvent(event)
  15. }
  16. }
  17. func (e *eventBus) AddSnowflakeEventListener(receiver SnowflakeEventReceiver) {
  18. e.lock.Lock()
  19. defer e.lock.Unlock()
  20. e.listeners = append(e.listeners, receiver)
  21. }
  22. func (e *eventBus) RemoveSnowflakeEventListener(receiver SnowflakeEventReceiver) {
  23. e.lock.Lock()
  24. defer e.lock.Unlock()
  25. var newListeners []SnowflakeEventReceiver
  26. for _, v := range e.listeners {
  27. if v != receiver {
  28. newListeners = append(newListeners, v)
  29. }
  30. }
  31. e.listeners = newListeners
  32. return
  33. }