channel/merge.go

29 lines
514 B
Go
Raw Normal View History

2022-02-09 12:10:02 +01:00
package channel
import "sync"
// Merge returns a channel in which all values of all incoming channels are sent to.
// The values will be sent in the same order as they are received
func Merge[T any](channels ...<-chan T) <-chan T {
out := make(chan T, determineBufferSize(channels))
var wg sync.WaitGroup
wg.Add(len(channels))
for _, ch := range channels {
go func(ch <-chan T) {
for v := range ch {
out <- v
}
wg.Done()
}(ch)
}
go func() {
wg.Wait()
close(out)
}()
return out
}