summaryrefslogtreecommitdiffstats
path: root/core/src/subscription.rs
blob: 1e6695d6d383f0667b9aece9031a474880e209eb (plain) (blame)
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
//! Generate events asynchronously for you application.

/// An event subscription.
pub struct Subscription<T> {
    definitions: Vec<Box<dyn Definition<Message = T>>>,
}

impl<T> Subscription<T> {
    pub fn none() -> Self {
        Self {
            definitions: Vec::new(),
        }
    }

    pub fn batch(subscriptions: impl Iterator<Item = Subscription<T>>) -> Self {
        Self {
            definitions: subscriptions
                .flat_map(|subscription| subscription.definitions)
                .collect(),
        }
    }

    pub fn definitions(self) -> Vec<Box<dyn Definition<Message = T>>> {
        self.definitions
    }
}

impl<T, A> From<A> for Subscription<T>
where
    A: Definition<Message = T> + 'static,
{
    fn from(definition: A) -> Self {
        Self {
            definitions: vec![Box::new(definition)],
        }
    }
}

/// The definition of an event subscription.
pub trait Definition {
    type Message;

    fn id(&self) -> u64;

    fn stream(
        &self,
    ) -> (
        futures::stream::BoxStream<'static, Self::Message>,
        Box<dyn Handle>,
    );
}

pub trait Handle {
    fn cancel(&mut self);
}

impl<T> std::fmt::Debug for Subscription<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Command").finish()
    }
}