Suppose I have a generator, that returns me some results broken up into chunks, that I want to pull into a flat list:
def pull(chunk: Chunk, result: Stream[Item] = Stream.empty): Stream[Item] = {
val soFar = chunk.items ++ result
if(chunk.hasNext) pull(generator.next(chunk), soFar) else soFar
}
Conceptually, this is what I want, except, it fetches the entire content upfront, and I want it to be lazy. Something like this:
Stream.iterate(generator.first)(generator.next)
.takeWhile(_.hasNext)
.flatMap(_.items)
almost works, but it discards the last chunk.
It seems like I need a .takeUntil
here: like takeWhile
, but go through the entire chain before terminating. How do I do this idiomatically?