From c403dd3a2a75a5c61ee280d5e6c87ee99c7a5788 Mon Sep 17 00:00:00 2001 From: Lee Sang Gyu Date: Mon, 9 Nov 2026 13:30:17 +0900 Subject: [PATCH] fix(package): [concurrency] stop Take when the source closes (#424) * fix(package): [concurrency] stop Take when the source closes * test(package): [concurrency] cover Take with closed and idle source --- concurrency/channel.go | 11 ++++++++++- concurrency/channel_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/concurrency/channel.go b/concurrency/channel.go index 876d14e..2a2fdf3 100644 --- a/concurrency/channel.go +++ b/concurrency/channel.go @@ -90,7 +90,16 @@ func (c *Channel[T]) Take(ctx context.Context, valueStream <-chan T, number int) select { case <-ctx.Done(): return - case takeStream <- <-valueStream: + case v, ok := <-valueStream: + if !ok { + return + } + + select { + case <-ctx.Done(): + return + case takeStream <- v: + } } } }() diff --git a/concurrency/channel_test.go b/concurrency/channel_test.go index 4c9da23..1f7f503 100644 --- a/concurrency/channel_test.go +++ b/concurrency/channel_test.go @@ -82,6 +82,34 @@ func TestTake(t *testing.T) { assert.Equal(3, <-intStream) } +func TestTake_sourceClosedOrCanceled(t *testing.T) { + t.Parallel() + assert := internal.NewAssert(t, "TestTake_sourceClosedOrCanceled") + + c := NewChannel[int]() + + // the source ends before number values: no zero values are produced + ctx := context.Background() + var got []int + for v := range c.Take(ctx, c.Generate(ctx, 1, 2), 5) { + got = append(got, v) + } + assert.Equal([]int{1, 2}, got) + + // the source is idle: canceling ctx closes the stream + ctx2, cancel := context.WithCancel(context.Background()) + idle := make(chan int) + stream := c.Take(ctx2, idle, 3) + cancel() + + select { + case _, ok := <-stream: + assert.Equal(false, ok) + case <-time.After(2 * time.Second): + t.Fatal("Take did not stop after the context was canceled") + } +} + func TestFanIn(t *testing.T) { t.Parallel() assert := internal.NewAssert(t, "TestFanIn")