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
use futures::sync::mpsc::SendError;
use futures::sync::mpsc::UnboundedSender;

pub struct UnboundedSenderWithFinal<T> {
    sender: UnboundedSender<T>,
    last: Option<T>,
}

impl<T> UnboundedSenderWithFinal<T> {
    pub fn new(sender: UnboundedSender<T>, last: T) -> UnboundedSenderWithFinal<T> {
        UnboundedSenderWithFinal {
            sender: sender,
            last: Some(last),
        }
    }

    pub fn send(&self, msg: T) -> Result<(), SendError<T>> {
        self.sender.send(msg)
    }

    pub fn cancel_last(&mut self) {
        self.last.take();
    }
}

impl<T> Drop for UnboundedSenderWithFinal<T> {
    fn drop(&mut self) {
        if let Some(last) = self.last.take() {
            drop(self.sender.send(last));
        }
    }
}