use std::pin::Pin; use std::task::{Context, Poll}; use futures::Stream; use tokio::sync::mpsc; /// Using unbounded channels to prevent users from blocking internal logic ( e.g: ws heartbeat ) /// Users must listen to all events to avoid the process from running out of memory #[derive(Clone, Debug)] pub struct Emitter { tx: mpsc::UnboundedSender, } impl Emitter { pub fn new() -> (Self, mpsc::UnboundedReceiver) { let (tx, rx) = mpsc::unbounded_channel(); (Self { tx }, rx) } pub fn event(&self, event: T) { let _ = self.tx.send(event); } } #[derive(Debug)] pub struct Events { rx: mpsc::UnboundedReceiver, } impl Events { pub fn new(rx: mpsc::UnboundedReceiver) -> Self { Self { rx } } } impl Stream for Events { type Item = T; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { self.rx.poll_recv(cx) } }