fix(tea): allocate msgs channel in constructor

Race condition bug: Start() is called in a new gorotuine, then Send(). If the
Send happens before the msgs channel is allocated, the message is dropped.

Instead allocate the channel in the constructor, so msgs is never nil.

Signed-off-by: Christian Stewart <christian@paral.in>
This commit is contained in:
Christian Stewart 2022-01-03 23:33:28 -08:00 committed by Christian Rocha
parent 66cea095eb
commit 608fde59ed
1 changed files with 2 additions and 5 deletions

5
tea.go
View File

@ -239,6 +239,7 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
initialModel: model, initialModel: model,
output: os.Stdout, output: os.Stdout,
input: os.Stdin, input: os.Stdin,
msgs: make(chan Msg),
CatchPanics: true, CatchPanics: true,
} }
@ -252,8 +253,6 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
// StartReturningModel initializes the program. Returns the final model. // StartReturningModel initializes the program. Returns the final model.
func (p *Program) StartReturningModel() (Model, error) { func (p *Program) StartReturningModel() (Model, error) {
p.msgs = make(chan Msg)
var ( var (
cmds = make(chan Cmd) cmds = make(chan Cmd)
errs = make(chan error) errs = make(chan error)
@ -554,9 +553,7 @@ func (p *Program) Start() error {
// This method is currently provisional. The method signature may alter // This method is currently provisional. The method signature may alter
// slightly, or it may be removed in a future version of this package. // slightly, or it may be removed in a future version of this package.
func (p *Program) Send(msg Msg) { func (p *Program) Send(msg Msg) {
if p.msgs != nil {
p.msgs <- msg p.msgs <- msg
}
} }
// Quit is a convenience function for quitting Bubble Tea programs. Use it // Quit is a convenience function for quitting Bubble Tea programs. Use it