1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::fmt::Display;

use log::error;

pub trait Listener<M>: Send {
    fn notify(&self, msg: M) -> Result<(), NotifyError>;
}

pub enum NotifyError {
    Unsubscribe,
    Full,
    Other(Box<dyn Display>),
}


pub struct Listeners<M> {
    pub(crate) listeners: Vec<Box<dyn Listener<M>>>,
}

impl<M: Clone> Listeners<M> {
    pub fn add_with_initial_msg(&mut self, listener: Box<dyn Listener<M>>, initial: Option<M>) {
        if let Some(initial) = initial {
            if listener.notify(initial).is_ok() {
                self.add(listener);
            }
        } else {
            self.add(listener);
        }
    }

    pub fn add(&mut self, listener: Box<dyn Listener<M>>) {
        self.listeners.push(listener);
    }

    pub fn emit(&mut self, msg: M) {
        self.listeners
            .retain(|listener| match listener.notify(msg.clone()) {
                Ok(()) => true,
                Err(NotifyError::Full) => true,
                Err(NotifyError::Unsubscribe) => false,
                Err(NotifyError::Other(err)) => {
                    // TODO(design): display backtrace info here
                    error!("Error in listener {}", err);
                    true
                }
            });
    }
}

impl<M> Default for Listeners<M> {
    fn default() -> Self {
        Self {
            listeners: Vec::new(),
        }
    }
}

impl <M: 'static + Send> Listener<M> for futures::channel::mpsc::UnboundedSender<M> {
    fn notify(&self, msg: M) -> Result<(), NotifyError> {
        self.unbounded_send(msg).map_err(|err| if err.is_full() {
            NotifyError::Full
        } else if err.is_disconnected() {
            NotifyError::Unsubscribe
        } else {
            unreachable!()
        })
    }
}