datastream
datastream processes streams of values, text, and bytes in Gleam.
Use it to read input a piece at a time and run cleanup callbacks, such as closing a file, when a pipeline finishes or stops early. gleam/list works with a list already in memory; a datastream pipeline requests each next element as it runs. The synchronous core runs on Erlang and JavaScript. Parallel mapping and timers require Erlang.
Installation
gleam add datastream@0
Requires Gleam 1.14 or later.
Usage
import datastream
import gleam/io
import gleam/string
pub fn main() {
datastream.iterate(from: 1, with: fn(x) { x + 1 })
|> datastream.map(with: fn(x) { x * 2 })
|> datastream.take(up_to: 5)
|> datastream.to_list
|> string.inspect
|> io.println
}
This prints [2, 4, 6, 8, 10]. resource connects a pipeline to a file, socket, or cursor using open, next, and close callbacks. It opens on the first pull and closes once on completion, early termination, or when a callback raises. A pipeline that is never pulled opens nothing.
The API uses one import, datastream. See HexDocs for construction, transformations, terminals, text parsing, and binary framing.
Examples
The example pipelines run in the test suite:
- Count log levels from text split across chunks.
- Decode and parse records from a byte stream.
- Read length-prefixed frames.
- Map with parallel workers on Erlang.
- Validate rows with dataprep.
Resource and target behavior
Each terminal operation starts a fresh run of an ordinary pipeline. Consumers returned by broadcast, broadcast_bounded, or unzip share one upstream and are single-use. On Erlang, consume them in the process that created them. An unbounded broadcast retains unread values for slow consumers; use broadcast_bounded to report a queue overflow and close the upstream.
Text and binary parsers retain unfinished records between chunks. Memory use depends on the largest unfinished record. Length-prefixed framing accepts a frame-size limit.
On JavaScript, to_async_iterable exports a synchronous pipeline for a host for await loop. Breaking out of the loop closes the stream. The JavaScript adapter guide describes the adapter and its target-specific API.
Contributing
See CONTRIBUTING.md for setup and release verification, and the testing guide for properties and chunk-boundary checks.
License
MIT.
Contributors
Thanks goes to these people (emoji key):
CHIKAMATSU Naohiro 💻 📖 |
bitbloxhub 🤔 |
This project follows the all-contributors specification.