Skip to content

Commit

Permalink
Add repeatFn sample
Browse files Browse the repository at this point in the history
4. Concurrency Patterns in Go
->Pipelines
->Some Handy Generators
  • Loading branch information
mikutas committed Sep 14, 2020
1 parent 4e55fd7 commit 018426e
Showing 1 changed file with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 018426e

Please sign in to comment.