Schedule refreshes more consistently.
All checks were successful
Build & Test / Main (push) Successful in 1m1s

Instead of returning the `scheduleRefresh` command only after receiving
an `update` message, do it while handling the `refresh` message. For
this not to cause weird behavior, the refresh deadline should be shorter
than the refresh interval.
This commit is contained in:
Sam Fredrickson 2024-03-24 23:01:51 -07:00
parent 7b445a02a2
commit 2d991880ce

View File

@ -112,18 +112,19 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
return m, tea.Batch( return m, tea.Batch(
m.resumeIndicator, m.resumeIndicator,
m.refresh, m.refresh,
m.scheduleRefresh(),
) )
case update: case update:
commands := []tea.Cmd{m.scheduleRefresh()} var cmd tea.Cmd
if msg.err == nil { if msg.err == nil {
m.math = msg.math m.math = msg.math
refillProperties(&m) refillProperties(&m)
refillProjections(&m) refillProjections(&m)
commands = append(commands, m.stopIndicator()) cmd = m.stopIndicator()
} else { } else {
m.indicator.Style = indicatorErrorStyle m.indicator.Style = indicatorErrorStyle
} }
return m, tea.Batch(commands...) return m, cmd
case stopIndicator: case stopIndicator:
m.refreshing = false m.refreshing = false
return m, nil return m, nil
@ -149,7 +150,7 @@ type stopIndicator struct{}
func (m Model) refresh() tea.Msg { func (m Model) refresh() tea.Msg {
ctx, cancel := context.WithDeadline( ctx, cancel := context.WithDeadline(
context.Background(), context.Background(),
time.Now().Add(time.Second*15)) time.Now().Add(refreshDeadline))
defer cancel() defer cancel()
err := m.math.Refresh(ctx) err := m.math.Refresh(ctx)
if err != nil { if err != nil {
@ -166,7 +167,7 @@ func (m Model) resumeIndicator() tea.Msg {
} }
func (m Model) scheduleRefresh() tea.Cmd { func (m Model) scheduleRefresh() tea.Cmd {
return tea.Tick(time.Second*30, return tea.Tick(refreshInterval,
func(t time.Time) tea.Msg { func(t time.Time) tea.Msg {
return Msg{m.math.Asset, refresh{}} return Msg{m.math.Asset, refresh{}}
}) })
@ -175,12 +176,16 @@ func (m Model) scheduleRefresh() tea.Cmd {
func (m Model) stopIndicator() tea.Cmd { func (m Model) stopIndicator() tea.Cmd {
// wait a bit to stop the indicator, so that it's more obvious // wait a bit to stop the indicator, so that it's more obvious
// even when the refresh completes quickly. // even when the refresh completes quickly.
return tea.Tick(time.Millisecond*500, return tea.Tick(stopIndicatorDelay,
func(t time.Time) tea.Msg { func(t time.Time) tea.Msg {
return Msg{m.math.Asset, stopIndicator{}} return Msg{m.math.Asset, stopIndicator{}}
}) })
} }
var refreshInterval = time.Second * 30
var refreshDeadline = time.Second * 15
var stopIndicatorDelay = time.Millisecond * 500
func refillProperties(m *Model) { func refillProperties(m *Model) {
rows := []table.Row{ rows := []table.Row{
{"Asset", string(m.math.Asset)}, {"Asset", string(m.math.Asset)},