本页尚未翻译,因此以英文显示。 参与翻译

takeWhile

Yields values as long as a predicate returns true, then stops for good.

Iterable<A> takeWhile<A>(bool Function(A a) f, Iterable<A> iterable) FxAsyncIterable<A> takeWhileAsync<A>(FutureOr<bool> Function(A a) f, FxAsyncIterable<A> iterable) Fx<T> Fx.takeWhile(bool Function(T value) test) // chain FxAsync<T> FxAsync.takeWhile(FutureOr<bool> Function(T a) f)

Lecture

Where take counts values, takeWhile tests them. It yields elements one at a time and stops the instant f returns false — it never looks past that point, even if a later element would have passed. That makes it a natural fit for "consume until the data stops making sense" situations: a sorted stream up to a threshold, a log up to the first anomaly, and so on.

Because it's lazy and short-circuits on the first failure, it's cheap to run even over a huge or infinite source — it only ever evaluates the prefix that actually matches.

Demo 1 · Basics

Note that 2 at the end never gets a chance — the predicate already failed on 7:

Demo 2 · Async

Try it yourself

Exercise: keep temperatures only while they stay below 25.

Related: take — take by count instead of predicate · takeUntilInclusive — stop after (and including) the match · dropWhile — the inverse · filter — keeps matches everywhere, not just a prefix