Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lo.Buffer() can't be cancelled ? #570

Open
kkqy opened this issue Dec 16, 2024 · 0 comments
Open

lo.Buffer() can't be cancelled ? #570

kkqy opened this issue Dec 16, 2024 · 0 comments

Comments

@kkqy
Copy link

kkqy commented Dec 16, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant