Skip to content

23 · Concurrency

Produce an asynchronous stream

An async fn* yields values and may await between them. It returns AsyncIter<T>, consumed with for await. Each request advances the producer; closing the stream or breaking the loop cancels the producer and runs its cleanup.

On this page

An async fn* yields values and may await between them. It returns AsyncIter<T>, consumed with for await. Each request advances the producer; closing the stream or breaking the loop cancels the producer and runs its cleanup.

Complete example

Run this example locally with the installed CLI and host scheduler.

Produce an asynchronous stream.

02-async-generators.zolo
// Fetching pages is driven by the consumer. Breaking closes the producer.

let mut fetched = 0
let mut closed = 0

async fn fetch_page(id: int) -> int {
    sleep 1ms
    fetched += 1
    id * 10
}

async fn* pages(ids: [int]) -> int {
    defer { closed += 1 }
    for id in ids {
        yield await fetch_page(id)
    }
}

let source: AsyncIter<int> = pages([1, 2, 3])
assert(fetched == 0)
let mut total = 0
let mut count = 0
for await page in source {
    total += page
    count += 1
    if count == 2 { break }
}
assert(total == 30)
assert(fetched == 2)
assert(closed == 1)
print("pages: {count}, total: {total}, closed: {closed}")

Requires the Zolo CLI/host — open in the playground or run locally.

Reference

Reference · Source program

zolo run examples/features/75-syntax-four-async/02-async-generators.zolo --no-cache

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br