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![BoundDropDisposal::new(BoxedDisposal::new(disposable))])
24    }
25
26    pub fn new_with_disposal_callback(callback: impl FnOnce() + NecessarySendSync + 'dis) -> Self {
27        Self(vec![BoundDropDisposal::new(BoxedDisposal::new(
28            CallbackDisposal::new(callback),
29        ))])
30    }
31
32    pub fn append_disposable(&mut self, disposable: impl Disposable + NecessarySendSync + 'dis) {
33        self.0
34            .push(BoundDropDisposal::new(BoxedDisposal::new(disposable)));
35    }
36}
37
38impl Disposable for Subscription<'_> {
39    fn dispose(self) {
40        // drop self to call the dispose
41    }
42}
43
44impl<'dis, T> Add<T> for Subscription<'dis>
45where
46    T: Disposable + NecessarySendSync + 'dis,
47{
48    type Output = Subscription<'dis>;
49
50    #[inline]
51    fn add(mut self, other: T) -> Subscription<'dis> {
52        self.append_disposable(other);
53        self
54    }
55}