-
-
Notifications
You must be signed in to change notification settings - Fork 896
Closed
Description
some channels from third-party package won't be closed.
When the ctx is canceled, their goroutines will exit directly without closing the channel.
If I cannot ensure that ch
can be properly closed and need to cancel through ctx,
I suggest adding a ctx
parameter.
like this:
func BufferWithCtx[T any](ctx context.Context, ch <-chan T, size int) (collection []T, length int, readTime time.Duration, ok bool) {
buffer := make([]T, 0, size)
index := 0
now := time.Now()
for ; index < size; index++ {
select {
case item, ok := <-ch:
if !ok {
return buffer, index, time.Since(now), false
}
buffer = append(buffer, item)
case <-ctx.Done():
return buffer, index, time.Since(now), false
}
}
return buffer, index, time.Since(now), true
}
"BufferWithCtx" is more versatile than "BufferWithTimeout" because a timeout can be implemented through context.
goamaral
Metadata
Metadata
Assignees
Labels
No labels