2014-06-12 02:37:20 +08:00
|
|
|
package gobot
|
|
|
|
|
2015-07-21 05:45:46 +08:00
|
|
|
import "sync"
|
|
|
|
|
2014-07-14 11:27:38 +08:00
|
|
|
type callback struct {
|
|
|
|
f func(interface{})
|
|
|
|
once bool
|
|
|
|
}
|
|
|
|
|
2014-12-31 21:15:52 +08:00
|
|
|
// Event executes the list of Callbacks when Chan is written to.
|
2014-06-12 02:37:20 +08:00
|
|
|
type Event struct {
|
2015-07-21 05:45:46 +08:00
|
|
|
sync.Mutex
|
2014-07-14 11:27:38 +08:00
|
|
|
Callbacks []callback
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
|
|
|
|
2014-12-31 21:15:52 +08:00
|
|
|
// NewEvent returns a new Event which is now listening for data.
|
2014-06-12 02:37:20 +08:00
|
|
|
func NewEvent() *Event {
|
2015-07-21 05:45:46 +08:00
|
|
|
return &Event{}
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
|
|
|
|
2014-12-31 21:15:52 +08: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-12 02:37:20 +08:00
|
|
|
func (e *Event) Write(data interface{}) {
|
2015-07-21 05:45:46 +08:00
|
|
|
e.Lock()
|
|
|
|
defer e.Unlock()
|
2014-06-12 02:37:20 +08:00
|
|
|
|
2015-07-21 05:45:46 +08:00
|
|
|
tmp := []callback{}
|
|
|
|
for _, cb := range e.Callbacks {
|
|
|
|
go cb.f(data)
|
|
|
|
if !cb.once {
|
|
|
|
tmp = append(tmp, cb)
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|
|
|
|
}
|
2015-07-21 05:45:46 +08:00
|
|
|
e.Callbacks = tmp
|
2014-06-12 02:37:20 +08:00
|
|
|
}
|