pub struct Receiver<T> { /* private fields */ }
Expand description

Receives values from the associated Sender.

Instances are created by the channel function.

To turn this receiver into a Stream, you can use the WatchStream wrapper.

Implementations§

source§

impl<T> Receiver<T>

source

pub fn borrow(&self) -> Ref<'_, T>

Returns a reference to the most recently sent value.

This method does not mark the returned value as seen, so future calls to changed may return immediately even if you have already seen the value with a call to borrow.

Outstanding borrows hold a read lock on the inner value. This means that long-lived borrows could cause the producer half to block. It is recommended to keep the borrow as short-lived as possible. Additionally, if you are running in an environment that allows !Send futures, you must ensure that the returned Ref type is never held alive across an .await point, otherwise, it can lead to a deadlock.

The priority policy of the lock is dependent on the underlying lock implementation, and this type does not guarantee that any particular policy will be used. In particular, a producer which is waiting to acquire the lock in send might or might not block concurrent calls to borrow, e.g.:

Potential deadlock example
// Task 1 (on thread A)    |  // Task 2 (on thread B)
let _ref1 = rx.borrow();   |
                           |  // will block
                           |  let _ = tx.send(());
// may deadlock            |
let _ref2 = rx.borrow();   |
Examples
use tokio::sync::watch;

let (_, rx) = watch::channel("hello");
assert_eq!(*rx.borrow(), "hello");
source

pub fn borrow_and_update(&mut self) -> Ref<'_, T>

Returns a reference to the most recently sent value and marks that value as seen.

This method marks the current value as seen. Subsequent calls to changed will not return immediately until the Sender has modified the shared value again.

Outstanding borrows hold a read lock on the inner value. This means that long-lived borrows could cause the producer half to block. It is recommended to keep the borrow as short-lived as possible. Additionally, if you are running in an environment that allows !Send futures, you must ensure that the returned Ref type is never held alive across an .await point, otherwise, it can lead to a deadlock.

The priority policy of the lock is dependent on the underlying lock implementation, and this type does not guarantee that any particular policy will be used. In particular, a producer which is waiting to acquire the lock in send might or might not block concurrent calls to borrow, e.g.:

Potential deadlock example
// Task 1 (on thread A)                |  // Task 2 (on thread B)
let _ref1 = rx1.borrow_and_update();   |
                                       |  // will block
                                       |  let _ = tx.send(());
// may deadlock                        |
let _ref2 = rx2.borrow_and_update();   |
source

pub fn has_changed(&self) -> Result<bool, RecvError>

Checks if this channel contains a message that this receiver has not yet seen. The new value is not marked as seen.

Although this method is called has_changed, it does not check new messages for equality, so this call will return true even if the new message is equal to the old message.

Returns an error if the channel has been closed.

Examples
use tokio::sync::watch;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = watch::channel("hello");

    tx.send("goodbye").unwrap();

    assert!(rx.has_changed().unwrap());
    assert_eq!(*rx.borrow_and_update(), "goodbye");

    // The value has been marked as seen
    assert!(!rx.has_changed().unwrap());

    drop(tx);
    // The `tx` handle has been dropped
    assert!(rx.has_changed().is_err());
}
source

pub async fn changed(&mut self) -> Result<(), RecvError>

Waits for a change notification, then marks the newest value as seen.

If the newest value in the channel has not yet been marked seen when this method is called, the method marks that value seen and returns immediately. If the newest value has already been marked seen, then the method sleeps until a new message is sent by the Sender connected to this Receiver, or until the Sender is dropped.

This method returns an error if and only if the Sender is dropped.

Cancel safety

This method is cancel safe. If you use it as the event in a tokio::select! statement and some other branch completes first, then it is guaranteed that no values have been marked seen by this call to changed.

Examples
use tokio::sync::watch;

#[tokio::main]
async fn main() {
    let (tx, mut rx) = watch::channel("hello");

    tokio::spawn(async move {
        tx.send("goodbye").unwrap();
    });

    assert!(rx.changed().await.is_ok());
    assert_eq!(*rx.borrow(), "goodbye");

    // The `tx` handle has been dropped
    assert!(rx.changed().await.is_err());
}
source

pub async fn wait_for( &mut self, f: impl FnMut(&T) -> bool ) -> Result<Ref<'_, T>, RecvError>

Waits for a value that satisifes the provided condition.

This method will call the provided closure whenever something is sent on the channel. Once the closure returns true, this method will return a reference to the value that was passed to the closure.

Before wait_for starts waiting for changes, it will call the closure on the current value. If the closure returns true when given the current value, then wait_for will immediately return a reference to the current value. This is the case even if the current value is already considered seen.

The watch channel only keeps track of the most recent value, so if several messages are sent faster than wait_for is able to call the closure, then it may skip some updates. Whenever the closure is called, it will be called with the most recent value.

When this function returns, the value that was passed to the closure when it returned true will be considered seen.

If the channel is closed, then wait_for will return a RecvError. Once this happens, no more messages can ever be sent on the channel. When an error is returned, it is guaranteed that the closure has been called on the last value, and that it returned false for that value. (If the closure returned true, then the last value would have been returned instead of the error.)

Like the borrow method, the returned borrow holds a read lock on the inner value. This means that long-lived borrows could cause the producer half to block. It is recommended to keep the borrow as short-lived as possible. See the documentation of borrow for more information on this.

Examples
use tokio::sync::watch;

#[tokio::main]

async fn main() {
    let (tx, _rx) = watch::channel("hello");

    tx.send("goodbye").unwrap();

    // here we subscribe to a second receiver
    // now in case of using `changed` we would have
    // to first check the current value and then wait
    // for changes or else `changed` would hang.
    let mut rx2 = tx.subscribe();

    // in place of changed we have use `wait_for`
    // which would automatically check the current value
    // and wait for changes until the closure returns true.
    assert!(rx2.wait_for(|val| *val == "goodbye").await.is_ok());
    assert_eq!(*rx2.borrow(), "goodbye");
}
source

pub fn same_channel(&self, other: &Receiver<T>) -> bool

Returns true if receivers belong to the same channel.

Examples
let (tx, rx) = tokio::sync::watch::channel(true);
let rx2 = rx.clone();
assert!(rx.same_channel(&rx2));

let (tx3, rx3) = tokio::sync::watch::channel(true);
assert!(!rx3.same_channel(&rx2));

Trait Implementations§

source§

impl<T> Clone for Receiver<T>

source§

fn clone(&self) -> Receiver<T>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T> Debug for Receiver<T>
where T: Debug,

source§

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

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

impl<T> Drop for Receiver<T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<T> From<Receiver<T>> for WatchStream<T>
where T: 'static + Clone + Send + Sync,

source§

fn from(recv: Receiver<T>) -> WatchStream<T>

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Receiver<T>

§

impl<T> Send for Receiver<T>
where T: Send + Sync,

§

impl<T> Sync for Receiver<T>
where T: Send + Sync,

§

impl<T> Unpin for Receiver<T>

§

impl<T> !UnwindSafe for Receiver<T>

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Any for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

§

fn type_name(&self) -> &'static str

§

impl<T> AnySync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
§

impl<F, W, T, D> Deserialize<With<T, W>, D> for F
where W: DeserializeWith<F, T, D>, D: Fallible + ?Sized, F: ?Sized,

§

fn deserialize( &self, deserializer: &mut D ) -> Result<With<T, W>, <D as Fallible>::Error>

Deserializes using the given deserializer
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where 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.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The type for metadata in pointers and references to Self.
source§

impl<T> Same for T

§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where 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 T
where 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.
§

impl<T> Upcastable for T
where T: Any + Send + Sync + 'static,

§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

upcast boxed dyn
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more