calc_basic_builder/
calc_basic_builder.rs1use 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 last: Mutex<CalcState>,
59}
60
61impl Default for CalcSubscriber {
62 fn default() -> CalcSubscriber {
63 CalcSubscriber {
64 last: Default::default(),
65 }
66 }
67}
68
69impl Subscriber<CalcState, CalcAction> for CalcSubscriber {
70 fn on_notify(&self, state: &CalcState, action: &CalcAction) {
71 match action {
72 CalcAction::Add(_i) => {
73 println!(
74 "CalcSubscriber::on_notify: state:{:?} <- last {:?} + action:{:?}",
75 state,
76 self.last.lock().unwrap(),
77 action
78 );
79 }
80 CalcAction::Subtract(_i) => {
81 println!(
82 "CalcSubscriber::on_notify: state:{:?} <- last {:?} + action:{:?}",
83 state,
84 self.last.lock().unwrap(),
85 action
86 );
87 }
88 }
89 *self.last.lock().unwrap() = state.clone();
91 }
92}
93
94pub fn main() {
95 println!("Hello, Builder!");
96
97 let store =
98 StoreBuilder::new_with_reducer(CalcState::default(), Box::new(CalcReducer::default()))
99 .with_name("calc".to_string())
100 .build()
101 .unwrap();
102 println!("add subscriber");
103 store.add_subscriber(Arc::new(CalcSubscriber::default()));
104 let _ = store.dispatch(CalcAction::Add(1)).expect("no dispatch failed");
105
106 thread::sleep(std::time::Duration::from_secs(1));
107 println!("add more subscriber");
108 store.add_subscriber(Arc::new(CalcSubscriber::default()));
109 let _ = store.dispatch(CalcAction::Subtract(1));
110
111 store.stop();
113
114 assert_eq!(store.get_state().count, 0);
115}