Skip to main content

stream_query

Function stream_query 

Source
pub async fn stream_query<F>(
    claude: &Claude,
    cmd: &QueryCommand,
    handler: F,
) -> Result<CommandOutput>
where F: FnMut(StreamEvent),
Expand description

Execute a command with streaming output, calling a handler for each NDJSON line.

This spawns the claude process and reads stdout line-by-line, parsing each as a JSON event and passing it to the handler. Useful for progress tracking and real-time output processing.

Dropping the returned future mid-flight kills the spawned claude process and its owned Unix process group (SIGKILL). Descendants that leave the group are outside drop cleanup’s scope. Events already dispatched to the handler are not rolled back.

§Example

use claude_wrapper::{Claude, QueryCommand, OutputFormat};
use claude_wrapper::streaming::{StreamEvent, stream_query};

let claude = Claude::builder().build()?;

let cmd = QueryCommand::new("explain quicksort")
    .output_format(OutputFormat::StreamJson);

let output = stream_query(&claude, &cmd, |event: StreamEvent| {
    if let Some(t) = event.event_type() {
        println!("[{t}] {:?}", event.data);
    }
}).await?;