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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
package tui
import (
"time"
"github.com/grindlemire/go-tui/internal/debug"
)
type Watcher interface {
Start(eventQueue chan<- func(), stopCh <-chan struct{})
}
type ChannelWatcher[T any] struct {
ch <-chan T
handler func(T)
}
func NewChannelWatcher[T any](ch <-chan T, fn func(T)) *ChannelWatcher[T] {
return &ChannelWatcher[T]{
ch: ch,
handler: fn,
}
}
func Watch[T any](ch <-chan T, handler func(T)) Watcher {
return NewChannelWatcher(ch, handler)
}
func (w *ChannelWatcher[T]) Start(eventQueue chan<- func(), stopCh <-chan struct{}) {
go func() {
for {
select {
case <-stopCh:
return
case val, ok := <-w.ch:
if !ok {
return
}
v := val
select {
case eventQueue <- func() {
w.handler(v)
}:
case <-stopCh:
return
}
}
}
}()
}
type stateWatcher[T any] struct {
state *State[T]
handler func(T)
stopped chan struct{}
}
func OnChange[T any](state *State[T], handler func(T)) Watcher {
return &stateWatcher[T]{state: state, handler: handler}
}
func (w *stateWatcher[T]) Start(eventQueue chan<- func(), stopCh <-chan struct{}) {
w.handler(w.state.Get())
unbind := w.state.Bind(func(v T) {
w.handler(v)
})
go func() {
<-stopCh
unbind()
if w.stopped != nil {
close(w.stopped)
}
}()
}
type timerWatcher struct {
interval time.Duration
handler func()
}
func OnTimer(interval time.Duration, handler func()) Watcher {
return &timerWatcher{interval: interval, handler: handler}
}
func (w *timerWatcher) Start(eventQueue chan<- func(), stopCh <-chan struct{}) {
go func() {
debug.Log("timerWatcher started")
ticker := time.NewTicker(w.interval)
defer ticker.Stop()
for {
select {
case <-stopCh:
return
case <-ticker.C:
debug.Log("timerWatcher ticked")
select {
case eventQueue <- w.handler:
case <-stopCh:
return
}
}
}
}()
}
|