📎 Webclip
Elixir Streams
The post explains that Enum performs eager collection operations, while Stream describes lazy computations that are only realized when an Enum function forces them. It uses ranges, file and stdin streams, and stream constructors such as repeatedly, iterate, unfold, and resource to show how lazy composition works on large or infinite data.
Reading notes#
Enumtransforms collections immediately, whileStreamstores future computations.- Streams still work with
Enumbecause they implementEnumerable. Enum.to_listandEnum.takeforce a stream to run.- A large range can be mapped lazily, and only the requested items are computed.
- Streams can be composed with
filterandmapwithout realizing the whole collection. File.stream!returns file lines or bytes as a stream.IO.streamgives the same kind of interface for standard input.GenEvent.streamcreates a stream of events from aGenEventmanager.Stream.repeatedlybuilds an infinite stream by calling a function each time an item is requested.Stream.iteratestarts from an initial value and generates each next value from the previous one.Stream.unfolduses an accumulator and a generator function that returns{next_element, new_accumulator}.Stream.resourceis suited to streams that wrap external resources.- The GitHub example uses
Stream.resourceto fetch paginated API results lazily. process_pagehandles the end of pagination, the need to fetch another page, and the normal case that yields items.- The resulting API lets users query repositories with a stream-like interface and combine organizations with
Stream.flat_map.
