summaryrefslogtreecommitdiffstats
path: root/core/src/subscription.rs
blob: 4c021d75721f9c2f6515a5f3759ba284169ea5ad (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
//! Generate events asynchronously for you application.

/// An event subscription.
pub struct Subscription<I, O> {
    connections: Vec<Box<dyn Connection<Input = I, Output = O>>>,
}

impl<I, O> Subscription<I, O> {
    pub fn none() -> Self {
        Self {
            connections: Vec::new(),
        }
    }

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

    pub fn connections(
        self,
    ) -> Vec<Box<dyn Connection<Input = I, Output = O>>> {
        self.connections
    }
}

impl<I, O, T> From<T> for Subscription<I, O>
where
    T: Connection<Input = I, Output = O> + 'static,
{
    fn from(handle: T) -> Self {
        Self {
            connections: vec![Box::new(handle)],
        }
    }
}

/// The connection of an event subscription.
pub trait Connection {
    type Input;
    type Output;

    fn id(&self) -> u64;

    fn stream(
        &self,
        input: Self::Input,
    ) -> futures::stream::BoxStream<'static, Self::Output>;
}

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