Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.5 — Cancelling a Stream
LLM Engineering · Example 1 of 1

Stop early, close the stream, count what was saved

A fake provider counts the words it writes and the streams left open. The generator (Python, JavaScript) or the iterator (Java) has a cleanup that runs when it ends or is closed.

When the user presses Stop or leaves the page, close the stream so the provider can stop writing and your program frees its resources. Hiding the text while you keep reading does not stop anything.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write read_until(stream, stop_word) that reads pieces from a generator, joins them, and stops (closing the generator) as soon as a piece equals stop_word. Return the text read before the stop word.

02

Write a generator numbered(limit, log) that yields 1, 2, 3 up to limit and appends "closed" to the list log in a finally block. Show that breaking out and calling close() appends "closed".

Explain it without notes

01

What does cancelling a stream save, and what does it not save?

02

How do you cancel a streaming request in JavaScript, Python and Java?

03

Why does cleanup belong in a finally block or try-with-resources?

04

How must cancellation travel through a server that relays the stream?

Stop early, close the stream, count what was saved
Sign in to run this example in your browser.

Expected output

read to the end : shown 20 words, generated 20, saved 0, open streams 0
Stop after 5    : shown 5 words, generated 5, saved 15, open streams 0
Stop, no close  : shown 5 words, generated 5, saved 15, open streams 1