diff --git a/channels/channels.go b/channels/channels.go index 31a56ac..f0f4d1e 100644 --- a/channels/channels.go +++ b/channels/channels.go @@ -47,3 +47,11 @@ func Broadcast[T any](input <-chan T, outputs ...chan<- T) { } }() } + +// Drain drains the channel until it is closed. +func Drain[T any](input <-chan T) { + go func() { + for range input { + } + }() +} diff --git a/channels/channels_test.go b/channels/channels_test.go index d67a299..9b05f41 100644 --- a/channels/channels_test.go +++ b/channels/channels_test.go @@ -26,3 +26,17 @@ func TestJoin(t *testing.T) { return len(el) == 2 }, 1*time.Second, 10*time.Millisecond) } + +func TestDrain(t *testing.T) { + in := make(chan int) + + go func() { + in <- 1 + in <- 2 + close(in) + }() + + Drain(in) + + assert.Len(t, in, 0) +}