-
Notifications
You must be signed in to change notification settings - Fork 249
/
watcher.go
72 lines (61 loc) · 1.51 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package settingsevent
import (
"context"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log"
"github.com/status-im/status-go/multiaccounts/settings"
"github.com/status-im/status-go/services/wallet/async"
)
type SettingChangeCb func(setting settings.SettingField, value interface{})
// Watcher executes a given callback whenever an account gets added/removed
type Watcher struct {
feed *event.Feed
group *async.Group
callback SettingChangeCb
}
func NewWatcher(feed *event.Feed, callback SettingChangeCb) *Watcher {
return &Watcher{
feed: feed,
callback: callback,
}
}
func (w *Watcher) Start() {
if w.group != nil {
return
}
w.group = async.NewGroup(context.Background())
w.group.Add(func(ctx context.Context) error {
return watch(ctx, w.feed, w.callback)
})
}
func (w *Watcher) Stop() {
if w.group != nil {
w.group.Stop()
w.group.Wait()
w.group = nil
}
}
func onSettingChanged(callback SettingChangeCb, setting settings.SettingField, value interface{}) {
if callback != nil {
callback(setting, value)
}
}
func watch(ctx context.Context, feed *event.Feed, callback SettingChangeCb) error {
ch := make(chan Event, 1)
sub := feed.Subscribe(ch)
defer sub.Unsubscribe()
for {
select {
case <-ctx.Done():
return nil
case err := <-sub.Err():
if err != nil {
log.Error("settings watcher subscription failed", "error", err)
}
case ev := <-ch:
if ev.Type == EventTypeChanged {
onSettingChanged(callback, ev.Setting, ev.Value)
}
}
}
}