You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
983 B

  1. package events
  2. // An EventCache buffers events for a Fireable
  3. // All events are cached. Filtering happens on Flush
  4. type EventCache struct {
  5. evsw Fireable
  6. events []eventInfo
  7. }
  8. // Create a new EventCache with an EventSwitch as backend
  9. func NewEventCache(evsw Fireable) *EventCache {
  10. return &EventCache{
  11. evsw: evsw,
  12. }
  13. }
  14. // a cached event
  15. type eventInfo struct {
  16. event string
  17. data EventData
  18. }
  19. // Cache an event to be fired upon finality.
  20. func (evc *EventCache) FireEvent(event string, data EventData) {
  21. // append to list (go will grow our backing array exponentially)
  22. evc.events = append(evc.events, eventInfo{event, data})
  23. }
  24. // Fire events by running evsw.FireEvent on all cached events. Blocks.
  25. // Clears cached events
  26. func (evc *EventCache) Flush() {
  27. for _, ei := range evc.events {
  28. evc.evsw.FireEvent(ei.event, ei.data)
  29. }
  30. // Clear the buffer, since we only add to it with append it's safe to just set it to nil and maybe safe an allocation
  31. evc.events = nil
  32. }