Created
July 4, 2021 23:11
-
-
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`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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