main.go
This file
Path
examples/realtime/main.go
90 lines · 2.1 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23// A simple example that shows how to send activity to Bubble Tea in real-time4// through a channel.56import (7 "fmt"8 "math/rand"9 "os"10 "time"1112 "charm.land/bubbles/v2/spinner"13 tea "charm.land/bubbletea/v2"14)1516// A message used to indicate that activity has occurred. In the real world (for17// example, chat) this would contain actual data.18type responseMsg struct{}1920// 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// asynchronously.24func listenForActivity(sub chan struct{}) tea.Cmd {25 return func() tea.Msg {26 for {27 time.Sleep(time.Millisecond * time.Duration(rand.Int63n(900)+100)) // nolint:gosec28 sub <- struct{}{}29 }30 }31}3233// A command that waits for the activity on a channel.34func waitForActivity(sub chan struct{}) tea.Cmd {35 return func() tea.Msg {36 return responseMsg(<-sub)37 }38}3940type 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}4647func (m model) Init() tea.Cmd {48 return tea.Batch(49 m.spinner.Tick,50 listenForActivity(m.sub), // generate activity51 waitForActivity(m.sub), // wait for activity52 )53}5455func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {56 switch msg.(type) {57 case tea.KeyPressMsg: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}7172func (m model) View() tea.View {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 tea.NewView(s)78}7980func main() {81 p := tea.NewProgram(model{82 sub: make(chan struct{}),83 spinner: spinner.New(),84 })8586 if _, err := p.Run(); err != nil {87 fmt.Println("could not start program:", err)88 os.Exit(1)89 }90}