Skip to content

Instantly share code, notes, and snippets.

@leonardo5621
Last active November 14, 2022 13:29
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 leonardo5621/9dffff4c9cee30efe9524cc15eb29eda to your computer and use it in GitHub Desktop.
Save leonardo5621/9dffff4c9cee30efe9524cc15eb29eda to your computer and use it in GitHub Desktop.
func fanIn(ctx context.Context, fetchers ...<-chan interface{}) <-chan interface{} {
combinedFetcher := make(chan interface{})
// 1
var wg sync.WaitGroup
wg.Add(len(fetchers))
// 2
for _, f := range fetchers {
f := f
go func() {
// 3
defer wg.Done()
for{
select{
case res := <-f:
combinedFetcher <- res
case <-ctx.Done():
return
}
}
}()
}
// 4
// Channel cleanup
go func() {
wg.Wait()
close(combinedFetcher)
} ()
return combinedFetcher
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment