github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/engine/broadcaster.go (about)

     1  package engine
     2  
     3  import "sync"
     4  
     5  // Notifiable is an interface for objects that can be notified
     6  type Notifiable interface {
     7  	// Notify sends a notification. This method must be concurrency safe and non-blocking.
     8  	// It is expected to be a Notifier object, but does not have to be.
     9  	Notify()
    10  }
    11  
    12  // Broadcaster is a distributor for Notifier objects. It implements a simple generic pub/sub pattern.
    13  // Callers can subscribe to single-channel notifications by passing a Notifier object to the Subscribe
    14  // method. When Publish is called, all subscribers are notified.
    15  type Broadcaster struct {
    16  	subscribers []Notifiable
    17  	mu          sync.RWMutex
    18  }
    19  
    20  // NewBroadcaster creates a new Broadcaster
    21  func NewBroadcaster() *Broadcaster {
    22  	return &Broadcaster{}
    23  }
    24  
    25  // Subscribe adds a Notifier to the list of subscribers to be notified when Publish is called
    26  func (b *Broadcaster) Subscribe(n Notifiable) {
    27  	b.mu.Lock()
    28  	defer b.mu.Unlock()
    29  
    30  	b.subscribers = append(b.subscribers, n)
    31  }
    32  
    33  // Publish sends notifications to all subscribers
    34  func (b *Broadcaster) Publish() {
    35  	b.mu.RLock()
    36  	defer b.mu.RUnlock()
    37  
    38  	for _, n := range b.subscribers {
    39  		n.Notify()
    40  	}
    41  }