Skip to content
Myr

Add example illustrating how to send messages via channels in realtime

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 dd6a0a0 · Browse files · 1 file+92 added−0 removed
This commit

State

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

1 file+92 added−0 removed

added:examples/realtime/main.go+92 added
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 "github.com/charmbracelet/bubbles/spinner"13 tea "github.com/charmbracelet/bubbletea"14)1516// A message used to indicate that activity has occured. 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// asyncronously.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))28 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 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.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}7172func (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}7980func main() {81 rand.Seed(time.Now().UTC().UnixNano())8283 p := tea.NewProgram(model{84 sub: make(chan struct{}),85 spinner: spinner.NewModel(),86 })8788 if p.Start() != nil {89 fmt.Println("could not start program")90 os.Exit(1)91 }92}