-
Notifications
You must be signed in to change notification settings - Fork 0
/
lifecycle.go
69 lines (61 loc) · 1.39 KB
/
lifecycle.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
59
60
61
62
63
64
65
66
67
68
69
package art
import (
"sync"
)
// Lifecycle define a management mechanism when init obj and terminate obj.
type Lifecycle struct {
initHandlers []func(adapter IAdapter) error
terminateHandlers []func(adapter IAdapter)
wg sync.WaitGroup
}
func (life *Lifecycle) OnConnect(inits ...func(adp IAdapter) error) *Lifecycle {
for _, init := range inits {
if init == nil {
continue
}
life.initHandlers = append(life.initHandlers, init)
}
return life
}
func (life *Lifecycle) OnDisconnect(terminates ...func(adp IAdapter)) *Lifecycle {
for _, terminate := range terminates {
if terminate == nil {
continue
}
life.terminateHandlers = append(life.terminateHandlers, terminate)
}
return life
}
func (life *Lifecycle) initialize(adp IAdapter) error {
for _, init := range life.initHandlers {
err := init(adp)
if err != nil {
life.syncTerminate(adp)
return err
}
}
return nil
}
func (life *Lifecycle) syncTerminate(adp IAdapter) {
n := len(life.terminateHandlers)
for i := n - 1; i >= 0; i-- {
terminate := life.terminateHandlers[i]
terminate(adp)
}
return
}
func (life *Lifecycle) asyncTerminate(adp IAdapter) {
n := len(life.terminateHandlers)
for i := n - 1; i >= 0; i-- {
terminate := life.terminateHandlers[i]
life.wg.Add(1)
go func() {
defer life.wg.Done()
terminate(adp)
}()
}
return
}
func (life *Lifecycle) wait() {
life.wg.Wait()
}