channel/timeout.go

31 lines
600 B
Go

package channel
import "time"
// CloseOnTimeout returns a channel which receives all values from the source.
// If no value was received in the given timeout duration, the returned channel will be closed.
// The input channel will not be closed.
func CloseOnTimeout[T any](source <-chan T, timeout time.Duration) <-chan T {
output := make(chan T, cap(source))
go func() {
defer close(output)
for {
timer := time.NewTimer(timeout)
select {
case value, ok := <-source:
if !ok {
return
}
output <- value
case <-timer.C:
return
}
}
}()
return output
}