1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add func in channel.go

This commit is contained in:
dudaodong
2022-04-19 16:21:23 +08:00
parent fc6dee9e77
commit 046e90486d
2 changed files with 42 additions and 0 deletions

View File

@@ -157,3 +157,27 @@ func (c *Channel) Or(channels ...<-chan any) <-chan any {
return orDone
}
// OrDone
func (c *Channel) OrDone(ctx context.Context, channel <-chan any) <-chan any {
resStream := make(chan any)
go func() {
defer close(resStream)
select {
case <-ctx.Done():
return
case v, ok := <-channel:
if !ok {
return
}
select {
case resStream <- v:
case <-ctx.Done():
}
}
}()
return resStream
}

View File

@@ -131,3 +131,21 @@ func TestOr(t *testing.T) {
assert.Equal(1, 1)
}
func TestOrDone(t *testing.T) {
assert := internal.NewAssert(t, "TestOrDone")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := NewChannel()
intStream := c.Take(ctx, c.Repeat(ctx, 1), 3)
var res any
for val := range c.OrDone(ctx, intStream) {
t.Logf("%v", val)
res = val
}
assert.Equal(1, res)
}