pub struct Receiver<T> { /* private fields */ }Expand description
Implementations§
Source§impl<T> Receiver<T>
impl<T> Receiver<T>
Sourcepub fn recv(self) -> Result<T, RecvError>
pub fn recv(self) -> Result<T, RecvError>
Attempts to wait for a value on this receiver, returning an error if the corresponding channel has hung up.
This function will always block the current thread if there is no data
available. Once a message is sent to the corresponding Sender,
this receiver will wake up and return that message.
If the corresponding Sender has disconnected, or it disconnects while
this call is blocking, this call will wake up and return Err to
indicate that no more messages can ever be received on this channel.
§Example
let (tx, rx) = sync_oneshot::channel();
let th_handle = std::thread::spawn(move || {
tx.send(5).unwrap();
});
th_handle.join().unwrap();
assert_eq!(5, rx.recv().unwrap());Sourcepub fn try_recv(&mut self) -> Result<T, TryRecvError>
pub fn try_recv(&mut self) -> Result<T, TryRecvError>
Attempts to return a pending value on this receiver without blocking.
This method will never block the caller in order to wait for data to become available. Instead, this will always return immediately with a possible option of pending data on the channel.
This is useful for a flavor of “optimistic check” before deciding to block on a receiver.
Compared with recv, this function has two failure cases instead of one (one for disconnection, one for an empty buffer).
Sourcepub fn close(&mut self)
pub fn close(&mut self)
Prevents the associated Sender handle from sending a value.
Any send operation which happens after calling close is guaranteed
to fail. After calling close, try_recv should be called to
receive a value if one was sent before the call to close
completed.
This function is useful to perform a graceful shutdown and ensure that a value will not be sent into the channel and never received.
close is no-op if a message is already received or the channel
is already closed.
§Examples
Prevent a value from being sent
use sync_oneshot::TryRecvError;
let (tx, mut rx) = sync_oneshot::channel();
assert!(!tx.is_closed());
rx.close();
assert!(tx.is_closed());
assert!(tx.send("never received").is_err());
match rx.try_recv() {
Err(TryRecvError::Closed) => {}
_ => unreachable!(),
}Receive a value sent before calling close
let (tx, mut rx) = sync_oneshot::channel();
assert!(tx.send("will receive").is_ok());
rx.close();
let msg = rx.try_recv().unwrap();
assert_eq!(msg, "will receive");