-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrate_limited_screen_updater.go
86 lines (69 loc) · 1.41 KB
/
rate_limited_screen_updater.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package reactor
import (
"sync"
"time"
)
type rateLimitedScreenUpdater struct {
sync.Mutex
ticker *time.Ticker
done chan interface{}
pendingUpdate *DisplayUpdate
parent func(*DisplayUpdate)
didUpdateParent bool
closed bool
}
func NewrateLimitedScreenUpdater(minDuration time.Duration, parent func(*DisplayUpdate)) *rateLimitedScreenUpdater {
ticker := time.NewTicker(minDuration)
done := make(chan interface{})
updater := &rateLimitedScreenUpdater{
ticker: ticker,
parent: parent,
done: done,
}
go func() {
for {
select {
case <-ticker.C:
updater.tick()
case _, ok := <-done:
if !ok {
return
}
}
}
}()
return updater
}
func (r *rateLimitedScreenUpdater) update(update *DisplayUpdate) {
r.Lock()
defer r.Unlock()
if r.closed {
return
}
if !r.didUpdateParent {
r.parent(update)
r.didUpdateParent = true
return
}
// do sent the update if there is something to eval, new title or new location
if update.Eval != "" || update.Title != "" || update.Location != "" {
r.parent(update)
}
r.pendingUpdate = update
}
func (r *rateLimitedScreenUpdater) tick() {
r.Lock()
defer r.Unlock()
if r.pendingUpdate != nil {
r.parent(r.pendingUpdate)
}
r.didUpdateParent = false
r.pendingUpdate = nil
}
func (r *rateLimitedScreenUpdater) close() {
r.Lock()
defer r.Unlock()
r.closed = true
r.ticker.Stop()
close(r.done)
}