github.com/pure-x-eth/consensus_tm@v0.0.0-20230502163723-e3c2ff987250/libs/events/event_cache.go (about)

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