rx_rust/disposable/
subscription.rs

1use crate::{
2    disposable::{
3        Disposable, bound_drop_disposal::BoundDropDisposal, boxed_disposal::BoxedDisposal,
4        callback_disposal::CallbackDisposal,
5    },
6    utils::types::NecessarySendSync,
7};
8use educe::Educe;
9use std::ops::Add;
10
11/// Subscription is from Observable pattern, it is used to unsubscribe the observable.
12/// The `dispose` method of `Disposable` will be called when the subscription is unsubscribe or dropped.
13#[derive(Educe)]
14#[educe(Debug, Default)]
15pub struct Subscription<'dis>(Vec<BoundDropDisposal<BoxedDisposal<'dis>>>);
16
17impl<'dis> Subscription<'dis> {
18    pub fn new() -> Self {
19        Self(Vec::default())
20    }
21
22    pub fn new_with_disposal(disposable: impl Disposable + NecessarySendSync + 'dis) -> Self {
23        Self(Vec::default()) + BoundDropDisposal::new(BoxedDisposal::new(disposable))
24    }
25
26    pub fn new_with_disposal_callback(callback: impl FnOnce() + NecessarySendSync + 'dis) -> Self {
27        Self(Vec::default())
28            + BoundDropDisposal::new(BoxedDisposal::new(CallbackDisposal::new(callback)))
29    }
30
31    pub fn append_disposable(&mut self, disposable: impl Disposable + NecessarySendSync + 'dis) {
32        self.0
33            .push(BoundDropDisposal::new(BoxedDisposal::new(disposable)));
34    }
35}
36
37impl Disposable for Subscription<'_> {
38    fn dispose(self) {
39        // drop self to call the dispose
40    }
41}
42
43impl<'dis, T> Add<T> for Subscription<'dis>
44where
45    T: Disposable + NecessarySendSync + 'dis,
46{
47    type Output = Subscription<'dis>;
48
49    #[inline]
50    fn add(mut self, other: T) -> Subscription<'dis> {
51        self.append_disposable(other);
52        self
53    }
54}