Rook
РусскийRU
// A stream fills a channel only as its reader makes room.
const input = new ReadableStream({
start(controller any) {
controller.enqueue("one")
controller.enqueue("two")
controller.close()
},
})
const chunks, failed = chan(input, 1)
for chunk in chunks {
console.log(chunk)
}
console.log("error:", <-failed)
move 7 of 7 · 1–0

Every result is received. The game is played.

Streams

chan(stream, size) turns a ReadableStream, such as the body of a fetch response, into a channel of its chunks, and gives a second channel that gets the error of the stream, or null at its end. The next chunk is read only when the last one is in the channel, so the room of the channel is the backpressure of the stream, and a goroutine in another thread can read it. close(chunks) cancels the stream.

stream(ch) is the other way: a ReadableStream of the values of a channel, which ends when the channel is closed, to give as the body of a Response or to pipeTo somewhere.

The task board can use a stream for its activity feed: incoming chunks become events for the app to process, while the channel's capacity provides backpressure if the worker falls behind.

// chan(stream) turns a ReadableStream into a channel, and stream(ch) a channel into a stream
interface Product {
    title string
    price number
}

// A goroutine in another thread gets the body chunk by chunk, as it comes over the network
async func parse(chunks <-chan string) (Product[], number) {
    let text = ""
    let count = 0
    for chunk in chunks {
        text += chunk
        count++
    }
    return JSON.parse(text) as Product[], count
}

const response = await fetch("https://fakestoreapi.com/products")
const text = response.body?.pipeThrough(new TextDecoderStream())

// The body is read no further ahead than the 4 chunks the channel has room for
const chunks, failed = chan(text, 4)
const products, count = await go parse(chunks)
console.log(`${products.length} products in ${count} chunks`)
console.log("error:", <-failed)

// The other way: a channel of lines is the body of a Response
const lines = chan<string>()
async func list() {
    for product in products.slice(0, 3) {
        lines <- `${product.title}: $${product.price}\n`
    }
    close(lines)
}
list()
const body = stream(lines).pipeThrough(new TextEncoderStream())
console.log(await new Response(body).text())