Skip to content

Commit aa0d45e

Browse files
committed
feat(extras/store): add Redux-like store impl.
1 parent 8a35c99 commit aa0d45e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

.extras/snippets/redux_store.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use std::sync::{RwLock, RwLockReadGuard};
2+
3+
#[allow(dead_code)]
4+
pub struct Store<T, U> {
5+
name: String,
6+
state: RwLock<T>,
7+
listeners: RwLock<Vec<fn(&T, &U)>>,
8+
reducer: fn(&mut T, &U),
9+
}
10+
11+
#[allow(dead_code)]
12+
impl<T, U> Store<T, U> {
13+
pub fn create_store<S: Into<String>>(name: S, reducer: fn(&mut T, &U), initial_state: T) -> Store<T, U> {
14+
Store {
15+
name: name.into(),
16+
state: RwLock::new(initial_state),
17+
listeners: RwLock::new(Vec::new()),
18+
reducer,
19+
}
20+
}
21+
22+
pub fn subscribe(&self, listener: fn(&T, &U)) {
23+
let mut listeners = self.listeners.write().expect("Could not write subscriber");
24+
listeners.push(listener);
25+
}
26+
27+
pub fn get_state(&self) -> RwLockReadGuard<T> {
28+
if let Err(_) = self.state.try_read() {
29+
warn!("Get State Called for `{}`, but would block", self.name);
30+
}
31+
32+
self.state.read().expect("Could not get state")
33+
}
34+
35+
pub fn dispatch(&self, action: U) {
36+
(self.reducer)(&mut self.state.write().expect("Could not write state"), &action);
37+
38+
for listener in &*self.listeners.read().expect("Could not notify listeners") {
39+
listener(&self.get_state(), &action)
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)