Reference · Browser

listen

signature
listen(str, fn) -> null

What it does

In a component's code, follows a stream the server sends (a route made with events or stream) for as long as the code that called it stands: f is called with each event's data (parsed as JSON when it is JSON, and the event's name as a second parameter when f declares one), each line of newline-delimited JSON, or each piece of text. A connection that drops is opened again (after a second, doubling up to 30 s, or after the retry the server last sent); a stream that ends is not. Opened again, it sends the last event id it had as Last-Event-ID, so a route that reads it can go on from there. It gives null.

Examples

in a program
route GET /jobs/:id/progress = events((send) => {    for step in range(10) {        work(id, step)        send({ done: step + 1, of: 10 }, "progress")    }})component Progress(job: int) {    state done = 0    listen(`/jobs/${job}/progress`, (p) => { done = p.done })    <progress value={done} max="10"/>}

With named events, the function takes the name second. The route sends prices, then a close that the component answers by setting the state its listen stands on:

in a program
route GET /prices/:symbol = events((send) => {    for _ in range(60) {                        // a minute of prices        send({ last: last_price(symbol) }, "price")        sleep(1000)    }    send({}, "close")})component Ticker(symbol: str) {    state price = null    state open = true    if open { listen(`/prices/${symbol}`, (p, event) => { if event == "close" { open = false } else { price = p.last } }) }    <span>{price ?? "..."}</span>}

Edge cases

print(listen("/progress", (p) => p))
output
null

Errors

A URL that is not a string, or a second argument that is not a function, is a runtime error, not an error value, on the server as in the browser.

this one fails
print(listen(42, (p) => p))
output
line 1: `listen` takes a URL and a function: listen("/progress", (p) => { done = p.done })

Chaining

listen is a statement: nothing is piped out of it. Its function is where the data goes on:

in a program
listen("/log", (line) => { lines = take(lines + [line], 100) })

See also

receive, events, stream, live, every, channel.open

Thread
9Useful? Like it, or add to its thread below.

Thread 0 posts

On listen(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo