Skip to content

Commit

Permalink
sync middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Elmer Bulthuis committed Dec 3, 2019
1 parent 6743fa0 commit 62cd4c8
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions examples/light/stores.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,39 @@
extern crate reduxr;

use super::*;
use reduxr::*;
use reduxr::Store;
use std::sync::Mutex;

pub fn create_store() -> Store<State, Action> {
let store: Store<State, _> = Store::default();
store.add_middleware(|next| {
let mutex = Mutex::new(());

Box::new(move |store, action| {
next(store, action);

if let Action::Switch = action {
let _lock = mutex.lock();
let state = store.get_state();
if state.select_power() {
store.dispatch(Action::TurnOff);
} else {
store.dispatch(Action::TurnOn);
}
};
next(store, action);
}
})
})
}

#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;

#[test]
fn test_store() {
let store = create_store();
let store_arc = Arc::new(create_store());
let store = store_arc.clone();

let state = store.get_state();
assert_eq!(state.select_power(), false);
Expand All @@ -46,5 +53,20 @@ mod tests {
store.dispatch(Action::Switch);
let state = store.get_state();
assert_eq!(state.select_power(), false);

for _ in 0..100 {
let threads: Vec<_> = (0..10)
.map(|_| store_arc.clone())
.map(|store| std::thread::spawn(move || store.dispatch(Action::Switch)))
.collect();

threads
.into_iter()
.for_each(|thread| thread.join().unwrap());

let store = store_arc.clone();
let state = store.get_state();
assert_eq!(state.select_power(), false);
}
}
}

0 comments on commit 62cd4c8

Please sign in to comment.