Skip to content
Myr

Update result example to use StartReturningModel

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 3a1b9fb · Browse files · 1 file+9 added−15 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+9 added−15 removed

  • other:+9 added−15 removed

1 file+9 added−15 removed

modified:examples/result/main.go+9 added-15 removed
1package main23// A simple example that shows how to retrieve a value from a Bubble Tea4// program after the Bubble Tea has exited.5//6// Thanks to Treilik for this one.56import (7 "fmt"8 "os"
5 unmodified lines
14var choices = []string{"Taro", "Coffee", "Lychee"}1516type model struct {17 cursor int20 choice chan string18 choice string19}2021func (m model) Init() tea.Cmd {22 return nil
3 unmodified lines
26 switch msg := msg.(type) {27 case tea.KeyMsg:28 switch msg.String() {29 case "ctrl+c", "q", "esc":32 close(m.choice) // If we're quitting just close the channel.30 return m, tea.Quit3132 case "enter":33 // Send the choice on the channel and exit.37 m.choice <- choices[m.cursor]34 m.choice = choices[m.cursor]35 return m, tea.Quit3637 case "down", "j":38 m.cursor++
31 unmodified lines
70 return s.String()71}7273func main() {77 // This is where we'll listen for the choice the user makes in the Bubble78 // Tea program.79 result := make(chan string, 1)74 p := tea.NewProgram(model{})7581 // Pass the channel to the initialize function so our Bubble Tea program82 // can send the final choice along when the time comes.83 p := tea.NewProgram(model{cursor: 0, choice: result})84 if err := p.Start(); err != nil {76 // StartReturningModel returns the model as a tea.Model.77 m, err := p.StartReturningModel()78 if err != nil {79 fmt.Println("Oh no:", err)80 os.Exit(1)81 }8289 // Print out the final choice.90 if r := <-result; r != "" {91 fmt.Printf("\n---\nYou chose %s!\n", r)83 // Assert the final tea.Model to our local model and print the choice.84 if m, ok := m.(model); ok && m.choice != "" {85 fmt.Printf("\n---\nYou chose %s!\n", m.choice)86 }87}