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.

39 lines
1.0 KiB

  1. package events
  2. import "context"
  3. // An EventCache buffers events for a Fireable
  4. // All events are cached. Filtering happens on Flush
  5. type EventCache struct {
  6. evsw Fireable
  7. events []eventInfo
  8. }
  9. // Create a new EventCache with an EventSwitch as backend
  10. func NewEventCache(evsw Fireable) *EventCache {
  11. return &EventCache{
  12. evsw: evsw,
  13. }
  14. }
  15. // a cached event
  16. type eventInfo struct {
  17. event string
  18. data EventData
  19. }
  20. // Cache an event to be fired upon finality.
  21. func (evc *EventCache) FireEvent(event string, data EventData) {
  22. // append to list (go will grow our backing array exponentially)
  23. evc.events = append(evc.events, eventInfo{event, data})
  24. }
  25. // Fire events by running evsw.FireEvent on all cached events. Blocks.
  26. // Clears cached events
  27. func (evc *EventCache) Flush(ctx context.Context) {
  28. for _, ei := range evc.events {
  29. evc.evsw.FireEvent(ctx, ei.event, ei.data)
  30. }
  31. // 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
  32. evc.events = nil
  33. }