pub struct StreamSender { /* private fields */ }Expand description
Sender half for streaming handlers.
Wraps a bounded tokio::sync::mpsc::Sender<String> and provides
ergonomic methods for sending typed items and checking cancellation.
The associated CancellationToken is automatically cancelled when
the StreamReceiver is dropped, enabling explicit cancellation checks
via tokio::select! in addition to is_closed().
§Example
async fn my_streaming_handler(args: MyArgs, tx: StreamSender) -> String {
let token = tx.cancellation_token();
loop {
tokio::select! {
_ = token.cancelled() => break,
item = next_item() => { tx.send(item).await.ok(); }
}
}
r#"{"done": true}"#.to_string()
}Note on Clone: Cloning a StreamSender shares the same underlying
channel and CancellationToken. Calling cancel() on any clone cancels
all of them.
Implementations§
Source§impl StreamSender
impl StreamSender
Sourcepub fn channel() -> (StreamSender, StreamReceiver)
pub fn channel() -> (StreamSender, StreamReceiver)
Create a new stream channel with the default capacity (64).
Returns (sender, receiver) pair. The CancellationToken is
automatically cancelled when the StreamReceiver is dropped.
Sourcepub fn with_capacity(capacity: usize) -> (StreamSender, StreamReceiver)
pub fn with_capacity(capacity: usize) -> (StreamSender, StreamReceiver)
Create a new stream channel with a custom capacity.
Returns (sender, receiver) pair.
Sourcepub fn cancellation_token(&self) -> CancellationToken
pub fn cancellation_token(&self) -> CancellationToken
Get the cancellation token for this stream.
The token is automatically cancelled when the StreamReceiver is
dropped, and can also be cancelled explicitly via cancel().
Use in tokio::select! for cooperative cancellation:
let token = tx.cancellation_token();
tokio::select! {
_ = token.cancelled() => { /* stream cancelled */ }
result = do_work() => { tx.send(result).await?; }
}Sourcepub fn cancel(&self)
pub fn cancel(&self)
Explicitly cancel the stream.
This cancels the CancellationToken, signalling handlers
that are using token.cancelled() in select!.
Sourcepub async fn send(&self, item: impl IntoStreamItem) -> Result<(), StreamError>
pub async fn send(&self, item: impl IntoStreamItem) -> Result<(), StreamError>
Send a stream item.
The item is converted to a JSON string via IntoStreamItem.
Returns StreamError::Closed if the receiver has been dropped,
or StreamError::Serialize if serialization fails.
Trait Implementations§
Source§impl Clone for StreamSender
impl Clone for StreamSender
Source§fn clone(&self) -> StreamSender
fn clone(&self) -> StreamSender
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more