mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
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
This commit is contained in:
1 parent
b4302b2d15
commit
c403dd3a2a
2 files changed
+38
-1
No files matched your search
+10
-1
@@ -90,7 +90,16 @@ func (c *Channel[T]) Take(ctx context.Context, valueStream <-chan T, number int)
|
|||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
case takeStream <- <-valueStream:
|
case v, ok := <-valueStream:
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case takeStream <- v:
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
@@ -82,6 +82,34 @@ func TestTake(t *testing.T) {
|
|||||||
assert.Equal(3, <-intStream)
|
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) {
|
func TestFanIn(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
assert := internal.NewAssert(t, "TestFanIn")
|
assert := internal.NewAssert(t, "TestFanIn")
|
||||||
|
|||||||
Reference in new issue
Block a user