Skip to content
Myr

Add 'Every' subscription for ticking with the system clock

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent b50ee76 · Browse files · 4 files+28 added−21 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+28 added−21 removed

  • other:+28 added−21 removed

4 files+28 added−21 removed

modified:examples/fullscreen/main.go+1 added-4 removed
53 unmodified lines
54}5556func subscriptions(_ tea.Model) tea.Subs {57 return tea.Subs{58 "tick": func() tea.Msg {59 time.Sleep(time.Second)60 return tickMsg{}61 },58 "tick": tea.Every(time.Second, tickMsg{}),59 }60}6162func view(mdl tea.Model) string {
3 unmodified lines
modified:examples/simple/main.go+4 added-5 removed
37 unmodified lines
38func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {39 m, _ := model.(Model)4041 switch msg.(type) {42 case tea.KeyMsg:43 return m, tea.Quit44 case TickMsg:45 m -= 146 if m <= 0 {47 return m, tea.Quit
5 unmodified lines
53// Views take data from the model and return a string which will be rendered54// to the terminal.55func view(model tea.Model) string {56 m, _ := model.(Model)55 return fmt.Sprintf("Hi. This program will exit in %d seconds...", m)57 return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.", m)58}5960// This is a subscription which we setup in NewProgram(). It waits for one61// second, sends a tick, and then restarts.62func subscriptions(_ tea.Model) tea.Subs {63 return tea.Subs{62 "tick": func() tea.Msg {63 time.Sleep(time.Second)64 return TickMsg{}65 },64 "tick": tea.Every(time.Second, TickMsg{}),65 }66}
modified:examples/views/main.go+2 added-12 removed
48 unmodified lines
49func subscriptions(model tea.Model) tea.Subs {50 m, _ := model.(Model)51 if !m.Chosen || m.Loaded {52 return tea.Subs{53 "tick": tick,53 "tick": tea.Every(time.Second, tickMsg{}),54 }55 }56 return tea.Subs{57 "frame": frame,57 "frame": tea.Every(time.Second/60, frameMsg{}),58 }59}6061func tick() tea.Msg {62 time.Sleep(time.Second)63 return tickMsg{}64}6566func frame() tea.Msg {67 time.Sleep(time.Second / 60)68 return frameMsg{}69}7061// UPDATES6263func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {64 m, _ := model.(Model)
154 unmodified lines
added:subscriptions.go+21 added
1package tea23import (4 "time"5)67// Every is a subscription that ticks with the system clock at the given8// duration9//10// TODO: make it cancelable11func Every(duration time.Duration, msg Msg) Sub {12 return func() Msg {13 n := time.Now()14 d := n.Truncate(duration).Add(duration).Sub(n)15 t := time.NewTimer(d)16 select {17 case <-t.C:18 return msg19 }20 }21}