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

/// An event subscription.
pub struct Subscription<T> {
    handles: Vec<Box<dyn Handle<Output = T>>>,
}

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

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

    pub fn handles(self) -> Vec<Box<dyn Handle<Output = T>>> {
        self.handles
    }
}

impl<T, A> From<A> for Subscription<T>
where
    A: Handle<Output = T> + 'static,
{
    fn from(handle: A) -> Self {
        Self {
            handles: vec![Box::new(handle)],
        }
    }
}

/// The handle of an event subscription.
pub trait Handle {
    type Output;

    fn id(&self) -> u64;

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

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