channel/timeout.go

31 lines
600 B
Go
Raw Normal View History

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.
2022-03-30 15:49:24 +02:00
// If no value was received in the given timeout duration, the returned channel will be closed.
// The input channel will not be closed.
2022-02-09 12:23:31 +01:00
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
}