Struct local_sync::oneshot::Sender

source ·
pub struct Sender<T> { /* private fields */ }
Expand description

Sends a value to the associated Receiver.

A pair of both a Sender and a Receiver are created by the channel function.

Implementations§

source§

impl<T> Sender<T>

source

pub fn send(self, t: T) -> Result<(), T>

Attempts to send a value on this channel, returning it back if it could not be sent.

This method consumes self as only one value may ever be sent on a oneshot channel. It is not marked async because sending a message to an oneshot channel never requires any form of waiting. Because of this, the send method can be used in both synchronous and asynchronous code without problems.

A successful send occurs when it is determined that the other end of the channel has not hung up already. An unsuccessful send would be one where the corresponding receiver has already been deallocated. Note that a return value of Err means that the data will never be received, but a return value of Ok does not mean that the data will be received. It is possible for the corresponding receiver to hang up immediately after this function returns Ok.

Examples

Send a value to another task

use local_sync::oneshot;

#[monoio::main]
async fn main() {
    let (tx, rx) = oneshot::channel();

    monoio::spawn(async move {
        if let Err(_) = tx.send(3) {
            println!("the receiver dropped");
        }
    });

    match rx.await {
        Ok(v) => println!("got = {:?}", v),
        Err(_) => println!("the sender dropped"),
    }
}
source

pub async fn closed(&mut self)

Waits for the associated Receiver handle to close.

A Receiver is closed by either calling close explicitly or the Receiver value is dropped.

This function is useful when paired with select! to abort a computation when the receiver is no longer interested in the result.

Return

Returns a Future which must be awaited on.

Examples

Basic usage

use local_sync::oneshot;

#[monoio::main]
async fn main() {
    let (mut tx, rx) = oneshot::channel::<()>();

    monoio::spawn(async move {
        drop(rx);
    });

    tx.closed().await;
    println!("the receiver dropped");
}

Paired with select

use local_sync::oneshot;
use monoio::time::{self, Duration};

async fn compute() -> String {
    // Complex computation returning a `String`
}

#[monoio::main]
async fn main() {
    let (mut tx, rx) = oneshot::channel();

    monoio::spawn(async move {
        monoio::select! {
            _ = tx.closed() => {
                // The receiver dropped, no need to do any further work
            }
            value = compute() => {
                // The send can fail if the channel was closed at the exact same
                // time as when compute() finished, so just ignore the failure.
                let _ = tx.send(value);
            }
        }
    });

    // Wait for up to 10 seconds
    let _ = time::timeout(Duration::from_secs(10), rx).await;
}
source

pub fn is_closed(&self) -> bool

Returns true if the associated Receiver handle has been dropped.

A Receiver is closed by either calling close explicitly or the Receiver value is dropped.

If true is returned, a call to send will always result in an error.

Examples
use local_sync::oneshot;

#[monoio::main]
async fn main() {
    let (tx, rx) = oneshot::channel();

    assert!(!tx.is_closed());

    drop(rx);

    assert!(tx.is_closed());
    assert!(tx.send("never received").is_err());
}
source

pub fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll<()>

Check whether the oneshot channel has been closed, and if not, schedules the Waker in the provided Context to receive a notification when the channel is closed.

A Receiver is closed by either calling close explicitly, or when the Receiver value is dropped.

Note that on multiple calls to poll, only the Waker from the Context passed to the most recent call will be scheduled to receive a wakeup.

Return value

This function returns:

  • Poll::Pending if the channel is still open.
  • Poll::Ready(()) if the channel is closed.
Examples
use local_sync::oneshot;

use futures_util::future::poll_fn;

#[monoio::main]
async fn main() {
    let (mut tx, mut rx) = oneshot::channel::<()>();

    monoio::spawn(async move {
        rx.close();
    });

    poll_fn(|cx| tx.poll_closed(cx)).await;

    println!("the receiver dropped");
}

Trait Implementations§

source§

impl<T: Debug> Debug for Sender<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T> Drop for Sender<T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Sender<T>

§

impl<T> !Send for Sender<T>

§

impl<T> !Sync for Sender<T>

§

impl<T> Unpin for Sender<T>

§

impl<T> !UnwindSafe for Sender<T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.