listener.go 964 字节
Newer Older
Y
Your Name 已提交
1 2 3 4 5 6 7
package listener

import "sync"

//CallbackFunc 回调函数
type CallbackFunc func(event interface{})

Y
Your Name 已提交
8
//Listener 监听者
Y
Your Name 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
type Listener struct {
	callbacks     []CallbackFunc
	callbacksOnce []CallbackFunc
	locker        sync.Mutex
}

//New 创建监听
func New() *Listener {
	return &Listener{
		callbacks:     nil,
		callbacksOnce: nil,
		locker:        sync.Mutex{},
	}
}

//ListenOnce listenOnce
func (l *Listener) ListenOnce(callbackFunc CallbackFunc) {
	l.locker.Lock()
	l.callbacksOnce = append(l.callbacksOnce, callbackFunc)
	l.locker.Unlock()
}

//Listen listen
func (l *Listener) Listen(callbackFunc CallbackFunc) {
	l.locker.Lock()
	l.callbacks = append(l.callbacks, callbackFunc)
	l.locker.Unlock()
}

//Call call
func (l *Listener) Call(event interface{}) {
	l.locker.Lock()
	cbs := l.callbacks
	cbsO := l.callbacksOnce
	l.callbacksOnce = nil
	l.locker.Unlock()

	for _, cb := range cbs {
		cb(event)
	}
	for _, cb := range cbsO {
		cb(event)
	}
}