1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-27 13:48:56 +08:00

36 lines
659 B
Go
Raw Normal View History

2014-06-11 11:37:20 -07:00
package gobot
import "sync"
2014-07-13 20:27:38 -07:00
type callback struct {
f func(interface{})
once bool
}
// Event executes the list of Callbacks when Chan is written to.
2014-06-11 11:37:20 -07:00
type Event struct {
sync.Mutex
2014-07-13 20:27:38 -07:00
Callbacks []callback
2014-06-11 11:37:20 -07:00
}
// NewEvent returns a new Event which is now listening for data.
2014-06-11 11:37:20 -07:00
func NewEvent() *Event {
return &Event{}
2014-06-11 11:37:20 -07:00
}
// Write writes data to the Event, it will not block and will not buffer if there
// are no active subscribers to the Event.
2014-06-11 11:37:20 -07:00
func (e *Event) Write(data interface{}) {
e.Lock()
defer e.Unlock()
2014-06-11 11:37:20 -07:00
tmp := []callback{}
for _, cb := range e.Callbacks {
go cb.f(data)
if !cb.once {
tmp = append(tmp, cb)
2014-06-11 11:37:20 -07:00
}
}
e.Callbacks = tmp
2014-06-11 11:37:20 -07:00
}