calc_query_state/
calc_query_state.rs

1use rs_store::DispatchOp;
2use rs_store::{Dispatcher, Reducer, StoreImpl};
3use std::sync::{Arc, Mutex};
4
5#[derive(Debug, Clone)]
6enum CalcAction {
7    Add(i32),
8    Subtract(i32),
9    Multiply(i32),
10    Reset,
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    history: Vec<String>,
25}
26
27impl Default for CalcState {
28    fn default() -> CalcState {
29        CalcState {
30            count: 0,
31            history: vec!["Initial state: 0".to_string()],
32        }
33    }
34}
35
36impl Reducer<CalcState, CalcAction> for CalcReducer {
37    fn reduce(&self, state: &CalcState, action: &CalcAction) -> DispatchOp<CalcState, CalcAction> {
38        match action {
39            CalcAction::Add(n) => {
40                let new_count = state.count + n;
41                let mut new_history = state.history.clone();
42                new_history.push(format!("Added {}: {} -> {}", n, state.count, new_count));
43                DispatchOp::Dispatch(
44                    CalcState {
45                        count: new_count,
46                        history: new_history,
47                    },
48                    vec![],
49                )
50            }
51            CalcAction::Subtract(n) => {
52                let new_count = state.count - n;
53                let mut new_history = state.history.clone();
54                new_history.push(format!(
55                    "Subtracted {}: {} -> {}",
56                    n, state.count, new_count
57                ));
58                DispatchOp::Dispatch(
59                    CalcState {
60                        count: new_count,
61                        history: new_history,
62                    },
63                    vec![],
64                )
65            }
66            CalcAction::Multiply(n) => {
67                let new_count = state.count * n;
68                let mut new_history = state.history.clone();
69                new_history.push(format!(
70                    "Multiplied by {}: {} -> {}",
71                    n, state.count, new_count
72                ));
73                DispatchOp::Dispatch(
74                    CalcState {
75                        count: new_count,
76                        history: new_history,
77                    },
78                    vec![],
79                )
80            }
81            CalcAction::Reset => {
82                let mut new_history = state.history.clone();
83                new_history.push(format!("Reset: {} -> 0", state.count));
84                DispatchOp::Dispatch(
85                    CalcState {
86                        count: 0,
87                        history: new_history,
88                    },
89                    vec![],
90                )
91            }
92        }
93    }
94}
95
96fn main() {
97    println!("=== Query State Example ===");
98
99    // Create a store with initial state
100    let store_impl =
101        StoreImpl::new_with_reducer(CalcState::default(), Box::new(CalcReducer::default()))
102            .unwrap();
103
104    // Dispatch some actions
105    println!("Dispatching actions...");
106    store_impl.dispatch(CalcAction::Add(10)).unwrap();
107    store_impl.dispatch(CalcAction::Multiply(2)).unwrap();
108    store_impl.dispatch(CalcAction::Subtract(5)).unwrap();
109
110    // Wait for actions to be processed
111    std::thread::sleep(std::time::Duration::from_millis(100));
112
113    // Query the current state using query_state
114    println!("\n=== Querying Current State ===");
115
116    // Query 1: Get current count
117    let current_count = Arc::new(Mutex::new(0));
118    let count_clone = current_count.clone();
119    store_impl
120        .query_state(move |state| {
121            *count_clone.lock().unwrap() = state.count;
122        })
123        .unwrap();
124
125    // Wait for actions to be processed
126    std::thread::sleep(std::time::Duration::from_millis(100));
127    println!("Current count: {}", *current_count.lock().unwrap());
128
129    // Query 2: Get history length
130    let history_length = Arc::new(Mutex::new(0));
131    let history_clone = history_length.clone();
132    store_impl
133        .query_state(move |state| {
134            *history_clone.lock().unwrap() = state.history.len();
135        })
136        .unwrap();
137
138    // Wait for actions to be processed
139    std::thread::sleep(std::time::Duration::from_millis(100));
140    println!("History length: {}", *history_length.lock().unwrap());
141
142    // Query 3: Print all history
143    println!("\n=== History ===");
144    store_impl
145        .query_state(|state| {
146            for (i, entry) in state.history.iter().enumerate() {
147                println!("  {}: {}", i + 1, entry);
148            }
149        })
150        .unwrap();
151
152    // Query 4: Check if count is even
153    let is_even = Arc::new(Mutex::new(false));
154    let even_clone = is_even.clone();
155    store_impl
156        .query_state(move |state| {
157            *even_clone.lock().unwrap() = state.count % 2 == 0;
158        })
159        .unwrap();
160
161    // Wait for actions to be processed
162    std::thread::sleep(std::time::Duration::from_millis(100));
163    println!("\nIs count even? {}", *is_even.lock().unwrap());
164
165    // Query 5: Get the last operation
166    let last_operation = Arc::new(Mutex::new(String::new()));
167    let last_op_clone = last_operation.clone();
168    store_impl
169        .query_state(move |state| {
170            if let Some(last) = state.history.last() {
171                *last_op_clone.lock().unwrap() = last.clone();
172            }
173        })
174        .unwrap();
175
176    // Wait for actions to be processed
177    std::thread::sleep(std::time::Duration::from_millis(100));
178    println!("Last operation: {}", *last_operation.lock().unwrap());
179
180    // Dispatch more actions and query again
181    println!("\n=== After More Actions ===");
182    store_impl.dispatch(CalcAction::Add(100)).unwrap();
183    store_impl.dispatch(CalcAction::Reset).unwrap();
184
185    // Wait for actions to be processed
186    std::thread::sleep(std::time::Duration::from_millis(100));
187
188    // Query final state
189    let final_count = Arc::new(Mutex::new(0));
190    let final_clone = final_count.clone();
191    store_impl
192        .query_state(move |state| {
193            *final_clone.lock().unwrap() = state.count;
194        })
195        .unwrap();
196
197    // Wait for actions to be processed
198    std::thread::sleep(std::time::Duration::from_millis(100));
199    println!("Final count: {}", *final_count.lock().unwrap());
200
201    // Query final history
202    println!("\n=== Final History ===");
203    store_impl
204        .query_state(|state| {
205            for (i, entry) in state.history.iter().enumerate() {
206                println!("  {}: {}", i + 1, entry);
207            }
208        })
209        .unwrap();
210
211    // Stop the store
212    store_impl.stop().unwrap();
213    println!("\nStore stopped.");
214}