Skip to content

Instantly share code, notes, and snippets.

@vaguecoder
Created July 4, 2021 23:11
Show Gist options
  • Save vaguecoder/e0ede95825b2a8a19553dd090404b028 to your computer and use it in GitHub Desktop.
Save vaguecoder/e0ede95825b2a8a19553dd090404b028 to your computer and use it in GitHub Desktop.
Broadcasts a message (any type) continuously in another goroutine. For full package/program, check `GitHub.com/VagueCoder/Random-Go-Snippets`.
// Channel is a custom type to hold channel and context variables.
type Channel struct {
// Only unexported fields
ch chan interface{}
ctx context.Context
cancelFunc context.CancelFunc
}
// runProducer is creates a separate goroutine that continuously produces given message.
// Unexported. No return values.
func (c *Channel) runProducer(msg interface{}) {
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
close(c.ch)
return
default:
c.ch <- msg
}
}
}(c.ctx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment