Skip to main content

spawn_stream

Function spawn_stream 

Source
pub fn spawn_stream<T, W, F, E>(work: W, on_item: F, on_end: E) -> Task
where T: Send + 'static, W: FnOnce(Emitter<T>) + Send + 'static, F: FnMut(T) + 'static, E: FnOnce() + 'static,
Expand description

Runs work on a background thread, handing it an Emitter, and runs on_item on this thread for every item it emits — in order, during the frames that follow. on_end runs once the worker returns.

The spawn_task shape for work that produces many values rather than one: a file watcher, a scan reporting progress, a paged download.

spawn_stream(
    |out| for path in walk_project() { out.emit(path); },
    move |path| found.update(|list| list.push(path)),
    move || scanning.set(false),
);

on_end fires after the last item, whether the worker returned or unwound — a stream cannot report why it stopped, only that it did. Cancelling instead drops both callbacks, so on_end does not run: the caller already knows, and is usually the one tearing that state down.

Everything posted between two frames is run in the next one, so a worker that emits faster than the UI can absorb makes for long frames. Emit coarse progress, not one item per unit of work.