Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add watch #1

Merged
merged 2 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions tokio-stream/src/wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ mod broadcast;
pub use broadcast::BroadcastStream;
pub use broadcast::BroadcastStreamRecvError;

mod watch;
pub use watch::WatchStream;

cfg_time! {
mod interval;
pub use interval::IntervalStream;
Expand Down
4 changes: 2 additions & 2 deletions tokio-stream/src/wrappers/broadcast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use tokio::sync::broadcast::Receiver;
use std::fmt;
use std::task::{Context, Poll};

/// A wrapper around [`Receiver`] that implements [`Stream`].
/// A wrapper around [`tokio::sync::broadcast::Receiver`] that implements [`Stream`].
///
/// [`Receiver`]: struct@tokio::sync::broadcast::Receiver
/// [`tokio::sync::broadcast::Receiver`]: struct@tokio::sync::broadcast::Receiver
/// [`Stream`]: trait@crate::Stream
pub struct BroadcastStream<T> {
inner: Pin<Box<dyn Stream<Item = Result<T, BroadcastStreamRecvError>> + Send + Sync>>,
Expand Down
50 changes: 50 additions & 0 deletions tokio-stream/src/wrappers/watch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use crate::Stream;
use async_stream::stream;
use std::pin::Pin;
use tokio::sync::watch::Receiver;

use std::fmt;
use std::task::{Context, Poll};

/// A wrapper around [`tokio::sync::watch::Receiver`] that implements [`Stream`].
///
/// [`tokio::sync::watch::Receiver`]: struct@tokio::sync::watch::Receiver
/// [`Stream`]: trait@crate::Stream
pub struct WatchStream<T> {
inner: Pin<Box<dyn Stream<Item = ()>>>,
_marker: std::marker::PhantomData<T>,
}

impl<T: 'static> WatchStream<T> {
/// Create a new `WatchStream`.
pub fn new(mut rx: Receiver<T>) -> Self {
let stream = stream! {
loop {
match rx.changed().await {
Ok(item) => yield item,
Err(_) => break,
}
}
};
Self {
inner: Box::pin(stream),
_marker: std::marker::PhantomData,
}
}
}

impl<T> Stream for WatchStream<T> {
type Item = ();

fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.inner).poll_next(cx)
}
}

impl<T> Unpin for WatchStream<T> {}

impl<T> fmt::Debug for WatchStream<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WatchStream").finish()
}
}