Skip to content

Commit cd8ff88

Browse files
committed
fix: send commands in a goroutine without executing them immediately
The commands channel handler handles commands and their execution. We should not execute them ourself in the event loop and instead send them to the commands channel where the handles will take care of executing them. Fixes: f5da8d0 (fix: handle nested SequenceMsg in event loop and use sync.WaitGroup f… (#1463))
1 parent f01583b commit cd8ff88

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

tea.go

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,17 @@ func (p *Program) disableMouse() {
377377
p.renderer.disableMouseSGRMode()
378378
}
379379

380+
// sendCmd a helper function to send a command to the program's command
381+
// channel. It will not block if the program is already shutting down, in which
382+
// case it will simply return without sending the command.
383+
func (p *Program) sendCmd(cmds chan Cmd, cmd Cmd) {
384+
select {
385+
case <-p.ctx.Done():
386+
return
387+
case cmds <- cmd:
388+
}
389+
}
390+
380391
// eventLoop is the central message loop. It receives and handles the default
381392
// Bubble Tea messages, update the model and triggers redraws.
382393
func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
@@ -475,7 +486,7 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
475486
if cmd == nil {
476487
continue
477488
}
478-
go p.Send(cmd())
489+
go p.sendCmd(cmds, cmd)
479490
}
480491
continue
481492

@@ -492,23 +503,16 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
492503
case BatchMsg:
493504
var wg sync.WaitGroup
494505
for _, cmd := range msg {
495-
if cmd == nil {
496-
continue
497-
}
498506
wg.Add(1)
499-
cmd := cmd
500507
go func() {
501508
defer wg.Done()
502-
p.Send(cmd())
509+
p.sendCmd(cmds, cmd)
503510
}()
504511
}
505512
wg.Wait()
506513
case sequenceMsg:
507514
for _, cmd := range msg {
508-
if cmd == nil {
509-
continue
510-
}
511-
p.Send(cmd())
515+
p.sendCmd(cmds, cmd)
512516
}
513517
default:
514518
p.Send(msg)

0 commit comments

Comments
 (0)