pocke.goevent/pfs.go

69 lines
990 B
Go
Raw Normal View History

2015-01-07 08:59:35 +08:00
package pfs
import (
"fmt"
"reflect"
"sync"
)
2015-01-07 21:24:56 +08:00
type PFS struct {
// funcs are listener functions.
funcs []reflect.Value
mu *sync.RWMutex
2015-01-07 08:59:35 +08:00
}
2015-01-07 21:24:56 +08:00
func New() *PFS {
return &PFS{
funcs: make([]reflect.Value, 0),
mu: &sync.RWMutex{},
}
}
func (p *PFS) Pub(args ...interface{}) {
p.mu.Lock()
defer p.mu.Unlock()
arguments := make([]reflect.Value, 0, len(args))
for _, v := range args {
arguments = append(arguments, reflect.ValueOf(v))
}
wg := sync.WaitGroup{}
wg.Add(len(p.funcs))
for _, fn := range p.funcs {
go func(f reflect.Value) {
defer wg.Done()
f.Call(arguments)
}(fn)
}
2015-01-07 08:59:35 +08:00
2015-01-07 21:24:56 +08:00
wg.Wait()
2015-01-07 08:59:35 +08:00
}
2015-01-07 21:24:56 +08:00
func (p *PFS) Sub(f interface{}) error {
2015-01-07 08:59:35 +08:00
p.mu.Lock()
defer p.mu.Unlock()
fn := reflect.ValueOf(f)
if reflect.Func != fn.Kind() {
return fmt.Errorf("Argument should be a function")
}
2015-01-07 21:24:56 +08:00
if len(p.funcs) != 0 {
2015-01-07 08:59:35 +08:00
// TODO: check fn arguments
}
2015-01-07 21:24:56 +08:00
p.funcs = append(p.funcs, fn)
2015-01-07 08:59:35 +08:00
return nil
}
2015-01-07 21:24:56 +08:00
func (p *PFS) Off() {
2015-01-07 08:59:35 +08:00
}
2015-01-07 21:24:56 +08:00
func (p *PFS) Filter(func() bool) {
2015-01-07 08:59:35 +08:00
}