github.com/decred/politeia@v1.4.0/politeiawww/legacy/events/events.go (about)

     1  // Copyright (c) 2020-2021 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package events
     6  
     7  import (
     8  	"sync"
     9  )
    10  
    11  // Manager manages event listeners.
    12  type Manager struct {
    13  	sync.Mutex
    14  	listeners map[string][]chan interface{}
    15  }
    16  
    17  // Register registers an event listener (channel) to listen for the provided
    18  // event type.
    19  func (e *Manager) Register(event string, listener chan interface{}) {
    20  	e.Lock()
    21  	defer e.Unlock()
    22  
    23  	l, ok := e.listeners[event]
    24  	if !ok {
    25  		l = make([]chan interface{}, 0)
    26  	}
    27  
    28  	l = append(l, listener)
    29  	e.listeners[event] = l
    30  
    31  	log.Debugf("Register event %v", event)
    32  }
    33  
    34  // Emit emits an event by passing it to all channels that have been registered
    35  // to listen for the event.
    36  func (e *Manager) Emit(event string, data interface{}) {
    37  	e.Lock()
    38  	defer e.Unlock()
    39  
    40  	listeners, ok := e.listeners[event]
    41  	if !ok {
    42  		return
    43  	}
    44  
    45  	for _, ch := range listeners {
    46  		ch <- data
    47  	}
    48  
    49  	log.Debugf("Emit event %v", event)
    50  }
    51  
    52  // NewManager returns a new Manager context.
    53  func NewManager() *Manager {
    54  	return &Manager{
    55  		listeners: make(map[string][]chan interface{}),
    56  	}
    57  }