Skip to content

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

@kkqy

Description

@kkqy

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions