-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
58 lines (48 loc) · 948 Bytes
/
watcher.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 handler
import (
"errors"
proto "github.com/itzmanish/go-micro/v2/config/source/service/proto"
)
type watcher struct {
id string
exit chan bool
next chan *proto.WatchResponse
}
func (w *watcher) Next() (*proto.WatchResponse, error) {
select {
case c := <-w.next:
return c, nil
case <-w.exit:
return nil, errors.New("watcher stopped")
}
}
func (w *watcher) Stop() error {
select {
case <-w.exit:
return errors.New("already stopped")
default:
close(w.exit)
}
mtx.Lock()
var wslice []*watcher
for _, watch := range watchers[w.id] {
if watch != w {
wslice = append(wslice, watch)
}
}
watchers[w.id] = wslice
mtx.Unlock()
return nil
}
// Watch created by a client RPC request
func Watch(id string) (*watcher, error) {
mtx.Lock()
w := &watcher{
id: id,
exit: make(chan bool),
next: make(chan *proto.WatchResponse),
}
watchers[id] = append(watchers[id], w)
mtx.Unlock()
return w, nil
}