/
client_eventwatcher.go
60 lines (49 loc) · 1.11 KB
/
client_eventwatcher.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
package cli
import (
"context"
"github.com/elliotchance/pie/v2"
)
func (c *Client) newEventWatcher(ctx context.Context, handler RecvEventHandler) *_EventWatcher {
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
watcher := &_EventWatcher{
Context: ctx,
terminate: cancel,
terminatedChan: make(chan struct{}),
client: c,
handler: handler,
}
c.eventWatchers.Append(watcher)
c.wg.Add(1)
go watcher.mainLoop()
return watcher
}
type _EventWatcher struct {
context.Context
terminate context.CancelFunc
terminatedChan chan struct{}
client *Client
handler RecvEventHandler
}
func (w *_EventWatcher) Terminate() <-chan struct{} {
w.terminate()
return w.terminatedChan
}
func (w *_EventWatcher) mainLoop() {
defer func() {
w.terminate()
w.client.wg.Done()
close(w.terminatedChan)
}()
select {
case <-w.Done():
case <-w.client.Done():
}
w.client.eventWatchers.AutoLock(func(watchers *[]*_EventWatcher) {
*watchers = pie.DropWhile(*watchers, func(other *_EventWatcher) bool {
return other == w
})
})
}