From 018426e83afde121843b3731ca5d7dcbe33a17e0 Mon Sep 17 00:00:00 2001 From: tkms0106 <23391543+tkms0106@users.noreply.github.com> Date: Mon, 14 Sep 2020 20:12:34 +0900 Subject: [PATCH] Add repeatFn sample 4. Concurrency Patterns in Go ->Pipelines ->Some Handy Generators --- .../fig-take-and-repeatfn-pipeline.go | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 concurrency-patterns-in-go/pipelines/some-handy-generators/fig-take-and-repeatfn-pipeline.go diff --git a/concurrency-patterns-in-go/pipelines/some-handy-generators/fig-take-and-repeatfn-pipeline.go b/concurrency-patterns-in-go/pipelines/some-handy-generators/fig-take-and-repeatfn-pipeline.go new file mode 100644 index 0000000..079093c --- /dev/null +++ b/concurrency-patterns-in-go/pipelines/some-handy-generators/fig-take-and-repeatfn-pipeline.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + repeatFn := func( + done <-chan interface{}, + fn func() interface{}, + ) <-chan interface{} { + valueStream := make(chan interface{}) + go func() { + defer close(valueStream) + for { + select { + case <-done: + return + case valueStream <- fn(): + } + } + }() + return valueStream + } + take := func( + done <-chan interface{}, + valueStream <-chan interface{}, + num int, + ) <-chan interface{} { + takeStream := make(chan interface{}) + go func() { + defer close(takeStream) + for i := 0; i < num; i++ { + select { + case <-done: + return + case takeStream <- <-valueStream: + } + } + }() + return takeStream + } + done := make(chan interface{}) + defer close(done) + + rand := func() interface{} { return rand.Int() } + + for num := range take(done, repeatFn(done, rand), 10) { + fmt.Println(num) + } +}