2022-02-09 12:10:02 +01:00
|
|
|
package channel
|
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
2022-02-09 12:23:31 +01:00
|
|
|
// 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
|
|
|
|
func CloseOnTimeout[T any](source <-chan T, timeout time.Duration) <-chan T {
|
|
|
|
output := make(chan T, cap(source))
|
2022-02-09 12:10:02 +01:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
defer close(output)
|
|
|
|
|
|
|
|
for {
|
|
|
|
timer := time.NewTimer(timeout)
|
|
|
|
|
|
|
|
select {
|
2022-02-09 12:23:31 +01:00
|
|
|
case value, ok := <-source:
|
2022-02-09 12:10:02 +01:00
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
output <- value
|
|
|
|
case <-timer.C:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return output
|
|
|
|
}
|