Last active
October 6, 2017 07:13
-
-
Save chrisvdg/3273430ddc9b85587ba1451d067748b8 to your computer and use it in GitHub Desktop.
Updating a channel every 5 messages
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
// 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