|
| 1 | +use std::future::Future; |
| 2 | + |
| 3 | +use async_broadcast::{broadcast, InactiveReceiver, Receiver, RecvError, SendError, Sender}; |
| 4 | +use dioxus::prelude::{to_owned, use_effect, ScopeState}; |
| 5 | +use uuid::Uuid; |
| 6 | + |
| 7 | +pub type UseListenChannelError = RecvError; |
| 8 | + |
| 9 | +/// Send and listen for messages between multiple components. |
| 10 | +#[derive(Debug, Clone)] |
| 11 | +pub struct UseChannel<MessageType: Clone> { |
| 12 | + id: Uuid, |
| 13 | + sender: Sender<MessageType>, |
| 14 | + inactive_receiver: InactiveReceiver<MessageType>, |
| 15 | +} |
| 16 | + |
| 17 | +impl<T: Clone> PartialEq for UseChannel<T> { |
| 18 | + fn eq(&self, other: &Self) -> bool { |
| 19 | + self.id == other.id |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<MessageType: Clone> UseChannel<MessageType> { |
| 24 | + /// Sends a message to all listeners of the channel. |
| 25 | + pub async fn send(&self, msg: impl Into<MessageType>) -> Result<(), SendError<MessageType>> { |
| 26 | + self.sender.broadcast(msg.into()).await.map(|_| ()) |
| 27 | + } |
| 28 | + |
| 29 | + /// Create a receiver for the channel. |
| 30 | + /// You probably want to use [`use_listen_channel`]. |
| 31 | + pub fn receiver(&mut self) -> Receiver<MessageType> { |
| 32 | + self.inactive_receiver.clone().activate() |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/// Send and listen for messages between multiple components. |
| 37 | +pub fn use_channel<MessageType: Clone + 'static>( |
| 38 | + cx: &ScopeState, |
| 39 | + size: usize, |
| 40 | +) -> UseChannel<MessageType> { |
| 41 | + let id = cx.use_hook(Uuid::new_v4); |
| 42 | + let (sender, inactive_receiver) = cx.use_hook(|| { |
| 43 | + let (sender, receiver) = broadcast::<MessageType>(size); |
| 44 | + |
| 45 | + (sender, receiver.deactivate()) |
| 46 | + }); |
| 47 | + |
| 48 | + UseChannel { |
| 49 | + id: *id, |
| 50 | + sender: sender.clone(), |
| 51 | + inactive_receiver: inactive_receiver.clone(), |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/// Create a messages listener for the given channel. |
| 56 | +pub fn use_listen_channel<MessageType: Clone + 'static, Handler>( |
| 57 | + cx: &ScopeState, |
| 58 | + channel: &UseChannel<MessageType>, |
| 59 | + action: impl Fn(Result<MessageType, UseListenChannelError>) -> Handler + 'static, |
| 60 | +) where |
| 61 | + Handler: Future<Output = ()> + 'static, |
| 62 | +{ |
| 63 | + use_effect(cx, (channel,), move |(channel,)| { |
| 64 | + to_owned![channel]; |
| 65 | + async move { |
| 66 | + let action = Box::new(action); |
| 67 | + let mut receiver = channel.receiver(); |
| 68 | + |
| 69 | + loop { |
| 70 | + let message = receiver.recv().await; |
| 71 | + let message_err = message.clone().err(); |
| 72 | + action(message).await; |
| 73 | + if message_err == Some(UseListenChannelError::Closed) { |
| 74 | + break; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + }); |
| 79 | +} |
0 commit comments