calc_unsubscribe/
calc_unsubscribe.rs

1use std::sync::{Arc, Mutex};
2use std::thread;
3
4use rs_store::{DispatchOp, StoreBuilder};
5use rs_store::{Reducer, Subscriber};
6
7#[derive(Debug, Clone)]
8enum CalcAction {
9    Add(i32),
10    Subtract(i32),
11}
12
13struct CalcReducer {}
14
15impl Default for CalcReducer {
16    fn default() -> CalcReducer {
17        CalcReducer {}
18    }
19}
20
21#[derive(Debug, Clone)]
22struct CalcState {
23    count: i32,
24}
25
26impl Default for CalcState {
27    fn default() -> CalcState {
28        CalcState { count: 0 }
29    }
30}
31
32impl Reducer<CalcState, CalcAction> for CalcReducer {
33    fn reduce(&self, state: &CalcState, action: &CalcAction) -> DispatchOp<CalcState, CalcAction> {
34        match action {
35            CalcAction::Add(i) => {
36                println!("CalcReducer::reduce: + {}", i);
37                DispatchOp::Dispatch(
38                    CalcState {
39                        count: state.count + i,
40                    },
41                    None,
42                )
43            }
44            CalcAction::Subtract(i) => {
45                println!("CalcReducer::reduce: - {}", i);
46                DispatchOp::Dispatch(
47                    CalcState {
48                        count: state.count - i,
49                    },
50                    None,
51                )
52            }
53        }
54    }
55}
56
57struct CalcSubscriber {
58    id: i32,
59    last: Mutex<CalcState>,
60}
61
62impl Default for CalcSubscriber {
63    fn default() -> CalcSubscriber {
64        CalcSubscriber {
65            id: 0,
66            last: Mutex::new(CalcState::default()),
67        }
68    }
69}
70
71impl CalcSubscriber {
72    fn new(id: i32) -> CalcSubscriber {
73        CalcSubscriber {
74            id,
75            last: Mutex::new(CalcState::default()),
76        }
77    }
78}
79
80impl Subscriber<CalcState, CalcAction> for CalcSubscriber {
81    fn on_notify(&self, state: &CalcState, action: &CalcAction) {
82        match action {
83            CalcAction::Add(_i) => {
84                println!(
85                    "CalcSubscriber::on_notify: id:{}, state: {:?} <- last: {:?} + action: {:?}",
86                    self.id,
87                    state,
88                    self.last.lock().unwrap(),
89                    action,
90                );
91            }
92            CalcAction::Subtract(_i) => {
93                println!(
94                    "CalcSubscriber::on_notify: id:{}, state: {:?} <- last: {:?} + action: {:?}",
95                    self.id,
96                    state,
97                    self.last.lock().unwrap(),
98                    action,
99                );
100            }
101        }
102
103        *self.last.lock().unwrap() = state.clone();
104    }
105}
106
107pub fn main() {
108    println!("Hello, Unsubscribe!");
109
110    let store =
111        StoreBuilder::new_with_reducer(CalcState::default(), Box::new(CalcReducer::default()))
112            .with_name("store-unsubscribe".into())
113            .build()
114            .unwrap();
115
116    println!("add subscriber");
117    store.add_subscriber(Arc::new(CalcSubscriber::default()));
118    let _ = store.dispatch(CalcAction::Add(1));
119
120    let store_clone = store.clone();
121    let handle = thread::spawn(move || {
122        thread::sleep(std::time::Duration::from_secs(1));
123
124        // subscribe
125        println!("add more subscriber");
126        let subscription = store_clone.add_subscriber(Arc::new(CalcSubscriber::new(1)));
127        let _ = store_clone.dispatch(CalcAction::Subtract(1));
128        subscription
129    });
130
131    let subscription = handle.join().unwrap();
132
133    println!("Unsubscribing...");
134    subscription.unsubscribe();
135
136    println!("Send 42...");
137    let _ = store.dispatch(CalcAction::Add(42));
138
139    store.stop();
140
141    println!("Done!");
142}