-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathupdater.go
72 lines (59 loc) · 1.18 KB
/
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
package skeleton
import (
tea "github.com/charmbracelet/bubbletea"
"sync"
)
type Updater struct {
rcv chan any
listening bool
mu sync.Mutex
}
var (
updaterInstance *Updater
onceUpdater sync.Once
)
func NewUpdater() *Updater {
onceUpdater.Do(func() {
updaterInstance = &Updater{
rcv: make(chan any, 256), // 256 is a reasonable buffer size for most cases, but it depends on your application's needs.
}
})
return updaterInstance
}
type UpdateMsg struct{}
var UpdateMsgInstance UpdateMsg
func (u *Updater) Listen() tea.Cmd {
u.mu.Lock()
defer u.mu.Unlock()
// Ensure only one listener is active
if u.listening {
return nil
}
u.listening = true
return func() tea.Msg {
// This function will block until a message is received
msg := <-u.rcv
u.mu.Lock()
u.listening = false
u.mu.Unlock()
return msg
}
}
func (u *Updater) Update() {
// Add non-blocking send
select {
case u.rcv <- UpdateMsgInstance:
// Successfully sent
default:
// Channel is full, skip update
}
}
func (u *Updater) UpdateWithMsg(msg any) {
// Add non-blocking send
select {
case u.rcv <- msg:
// Successfully sent
default:
// Channel is full, skip update
}
}