use super::run_event::RunEvent;
use crate::Result;
use flume::{Receiver, Sender};
pub struct RunQueue {
tx: RunTx,
rx: Option<RunRx>,
}
impl RunQueue {
pub fn new() -> Self {
let (tx, rx) = flume::unbounded();
Self {
tx: RunTx(tx),
rx: Some(RunRx(rx)),
}
}
pub fn start(&mut self) -> Result<RunTx> {
let rx = self.rx.take().ok_or_else(|| crate::Error::custom("RunQueue already started"))?;
tokio::spawn(async move {
while let Ok(event) = rx.recv().await {
println!("[RunEvent] - {event:?}");
}
});
Ok(self.sender())
}
pub fn sender(&self) -> RunTx {
self.tx.clone()
}
}
#[derive(Clone, Debug)]
pub struct RunTx(Sender<RunEvent>);
impl RunTx {
pub async fn send(&self, event: impl Into<RunEvent>) -> Result<()> {
let event = event.into();
self.0
.send_async(event)
.await
.map_err(|_| crate::Error::custom("RunQueue send async error, receiver dropped before sender"))
}
pub fn send_sync(&self, event: impl Into<RunEvent>) -> Result<()> {
let event = event.into();
self.0
.send(event)
.map_err(|_| crate::Error::custom("RunQueue send sync error, receiver dropped before sender"))
}
}
struct RunRx(Receiver<RunEvent>);
impl RunRx {
pub async fn recv(&self) -> Result<RunEvent> {
self.0
.recv_async()
.await
.map_err(|_| crate::Error::custom("RunQueue receive async error, sender dropped before receiver"))
}
}