-
Notifications
You must be signed in to change notification settings - Fork 22
/
handler.go
58 lines (44 loc) · 1.05 KB
/
handler.go
1
2
3
4
5
6
7
8
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
53
54
55
56
57
58
package fpgo
// HandlerDef Handler inspired by Android/WebWorker
type HandlerDef struct {
isClosed bool
ch chan func()
}
var defaultHandler *HandlerDef
// GetDefault Get Default Handler
func (handlerSelf *HandlerDef) GetDefault() *HandlerDef {
return defaultHandler
}
// New New Handler instance
func (handlerSelf *HandlerDef) New() *HandlerDef {
return handlerSelf.NewByCh(make(chan func()))
}
// NewByCh New Handler by its Channel
func (handlerSelf *HandlerDef) NewByCh(ioCh chan func()) *HandlerDef {
new := HandlerDef{ch: ioCh}
go new.run()
return &new
}
// Post Post a function to execute on the Handler
func (handlerSelf *HandlerDef) Post(fn func()) {
if handlerSelf.isClosed {
return
}
handlerSelf.ch <- fn
}
// Close Close the Handler
func (handlerSelf *HandlerDef) Close() {
handlerSelf.isClosed = true
close(handlerSelf.ch)
}
func (handlerSelf *HandlerDef) run() {
for fn := range handlerSelf.ch {
fn()
}
}
// Handler Handler utils instance
var Handler HandlerDef
func init() {
Handler = *Handler.New()
defaultHandler = &Handler
}