Skip to content

Instantly share code, notes, and snippets.

@chrisvdg
Last active October 6, 2017 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvdg/3273430ddc9b85587ba1451d067748b8 to your computer and use it in GitHub Desktop.
Save chrisvdg/3273430ddc9b85587ba1451d067748b8 to your computer and use it in GitHub Desktop.
Updating a channel every 5 messages
// https://play.golang.org/p/PWQlSox72E
package main
import (
"context"
"fmt"
"strconv"
"time"
)
const (
interval = 1
)
func main() {
messageInt := 1
ctx, cancel := context.WithCancel(context.Background())
messenger := newMessenger(ctx, "Message"+strconv.Itoa(messageInt))
for i := 0; i < 50; i++ {
if i%5 == 0 && i != 0 {
cancel()
ctx, cancel = context.WithCancel(context.Background())
messageInt++
messenger = newMessenger(ctx, "Message"+strconv.Itoa(messageInt))
}
select {
case message := <-messenger:
fmt.Println(message)
}
}
cancel()
}
func newMessenger(ctx context.Context, message string) <-chan string {
messenger := make(chan string)
ticker := time.NewTicker(interval * time.Millisecond)
go func() {
for {
select {
case <-ticker.C:
messenger <- message
case <-ctx.Done():
fmt.Printf("Print messenger for message '%s' closed\n", message)
return
}
}
}()
return messenger
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment