takeWhile
Yields values as long as a predicate returns true, then stops for good.
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.
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