Skip to content

Commit

Permalink
feat: add channel drain
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Oct 25, 2024
1 parent be975a6 commit 9101d61
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions channels/channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
}
}()
}
14 changes: 14 additions & 0 deletions channels/channels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Check failure on line 41 in channels/channels_test.go

View workflow job for this annotation

GitHub Actions / lint

empty: use assert.Empty (testifylint)

Check failure on line 41 in channels/channels_test.go

View workflow job for this annotation

GitHub Actions / test / lint

empty: use assert.Empty (testifylint)
}

0 comments on commit 9101d61

Please sign in to comment.