Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+92 added−0 removed
other:+92 added−0 removed
Provenance
Commit
91bd232
Tree
22920e9
Author
Christian Rocha <christian@rocha.is>
Committer
Christian Rocha <christian@rocha.is>
Parent
dd6a0a0
1 file changed+92 added−0 removed
added:examples/realtime/main.go+92 added
1+package main2+3+// A simple example that shows how to send activity to Bubble Tea in real-time4+// through a channel.5+6+import (7+ "fmt"8+ "math/rand"9+ "os"10+ "time"11+12+ "github.com/charmbracelet/bubbles/spinner"13+ tea "github.com/charmbracelet/bubbletea"14+)15+16+// A message used to indicate that activity has occured. In the real world (for17+// example, chat) this would contain actual data.18+type responseMsg struct{}19+20+// Simulate a process that sends events at an irregular interval in real time.21+// In this case, we'll send events on the channel at a random interval between22+// 100 to 1000 milliseconds. As a command, Bubble Tea will run this23+// asyncronously.24+func listenForActivity(sub chan struct{}) tea.Cmd {25+ return func() tea.Msg {26+ for {27+ time.Sleep(time.Millisecond * time.Duration(rand.Int63n(900)+100))28+ sub <- struct{}{}29+ }30+ }31+}32+33+// A command that waits for the activity on a channel.34+func waitForActivity(sub chan struct{}) tea.Cmd {35+ return func() tea.Msg {36+ return responseMsg(<-sub)37+ }38+}39+40+type model struct {41+ sub chan struct{} // where we'll receive activity notifications42+ responses int // how many responses we've received43+ spinner spinner.Model44+ quitting bool45+}46+47+func (m model) Init() tea.Cmd {48+ return tea.Batch(49+ spinner.Tick,50+ listenForActivity(m.sub), // generate activity51+ waitForActivity(m.sub), // wait for activity52+ )53+}54+55+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {56+ switch msg.(type) {57+ case tea.KeyMsg:58+ m.quitting = true59+ return m, tea.Quit60+ case responseMsg:61+ m.responses++ // record external activity62+ return m, waitForActivity(m.sub) // wait for next event63+ case spinner.TickMsg:64+ var cmd tea.Cmd65+ m.spinner, cmd = m.spinner.Update(msg)66+ return m, cmd67+ default:68+ return m, nil69+ }70+}71+72+func (m model) View() string {73+ s := fmt.Sprintf("\n %s Events received: %d\n\n Press any key to exit\n", m.spinner.View(), m.responses)74+ if m.quitting {75+ s += "\n"76+ }77+ return s78+}79+80+func main() {81+ rand.Seed(time.Now().UTC().UnixNano())82+83+ p := tea.NewProgram(model{84+ sub: make(chan struct{}),85+ spinner: spinner.NewModel(),86+ })87+88+ if p.Start() != nil {89+ fmt.Println("could not start program")90+ os.Exit(1)91+ }92+}