take
Returns a lazy iterable of the first length values from a source.
Lecture
take is how a lazy pipeline stays finite. It stops pulling
from its source the moment it has yielded length values —
the upstream never sees more requests than that. Because FxDart sources
like range, repeat, and cycle can
be infinite, take is often the only thing that makes a
pipeline safe to run at all.
It comes as a data-first function (take(n, iterable)) and as
a chain method (fx(iterable).take(n)). On the async side,
takeAsync/.take() is a pass-through: it doesn't
serialize the upstream, so a concurrent(n) further up the
chain keeps overlapping its pulls right up until take has
what it needs.
Demo 1 · Basics, and taking from an infinite source
cycle repeats its input forever — without
take, iterating it would never finish:
Demo 2 · Async, still overlapping under concurrent
Only 4 values are ever pulled here, but concurrent(3)
upstream still evaluates them 3-at-a-time — take doesn't
force everything sequential:
Try it yourself
Exercise: take only the first 3 names from the queue.
takeRight — last n instead of first n ·
takeWhile — take by predicate ·
range · cycle — infinite sources ·
concurrent — parallel evaluation