use std::error::Error;
use std::fmt;
use tokio::sync::watch;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurrentStateClosed;
impl fmt::Display for CurrentStateClosed {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("current-state publisher is closed")
}
}
impl Error for CurrentStateClosed {}
#[derive(Debug, Clone)]
pub struct CurrentState<T> {
receiver: watch::Receiver<T>,
}
impl<T> CurrentState<T> {
pub(crate) fn new(receiver: watch::Receiver<T>) -> Self {
Self { receiver }
}
}
impl<T> CurrentState<T>
where
T: Clone,
{
pub fn snapshot(&self) -> T {
self.receiver.borrow().clone()
}
pub async fn changed(&mut self) -> Result<T, CurrentStateClosed> {
self.receiver
.changed()
.await
.map_err(|_| CurrentStateClosed)?;
Ok(self.receiver.borrow_and_update().clone())
}
}