Photo by Perry Grone on Unsplash

There are some cases where you need to read enough items from a channel to begin processing. However, you also want to a TTL to expire with a smaller batch if there are not more items for a while.

Here’s an example of streaming a channel of string into an output channel of []string that guarantees:

Each batch contains at least one string. A batch will never contain more than maxItems . If there is at least one string to be read at any given time, it will always send a new batch within maxTimeout . A batch will contain less than maxItems if maxTimeout has occurred since the the last batch finished (not since the first item in the batch). This is important because it means that if the stream is scarce and infrequent — such as one item per maxTimeout — BatchStrings will prefer to send a consistently timed batch of one item rather than more volatile intervals that might contain two items.

Try it now: https://play.golang.org/p/5NqYwehuxr-