pub struct Store { /* private fields */ }Expand description
The Store struct holding multiple containers for different state types.
Implementations§
Source§impl Store
impl Store
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new, empty store.
§Returns
A new instance of Store.
§Examples
use sovran_state::Store;
let store = Store::new();Examples found in repository?
examples/sovran_example.rs (line 81)
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
fn main() {
// Create store and provide initial state
let store = Arc::new(Store::new());
store.provide(BankState {
balance: 1000.0,
transaction_count: 0,
}).expect("Failed to provide initial state");
// Create our components
let monitor = AccountMonitor::new(store.clone());
let _logger = TransactionLogger::new(store.clone());
println!("Initial balance: ${:.2}", monitor.check_balance());
// Simulate some transactions
println!("\nProcessing transactions...\n");
// Deposit
store.dispatch(DepositAction(500.0))
.expect("Failed to process deposit");
thread::sleep(Duration::from_millis(500));
// Withdraw
store.dispatch(WithdrawAction(200.0))
.expect("Failed to process withdrawal");
thread::sleep(Duration::from_millis(500));
// Deposit again
store.dispatch(DepositAction(750.0))
.expect("Failed to process deposit");
thread::sleep(Duration::from_millis(500));
println!("\nFinal balance: ${:.2}", monitor.check_balance());
}Sourcepub fn provide<S: State>(&self, initial_state: S) -> Result<(), StoreError>
pub fn provide<S: State>(&self, initial_state: S) -> Result<(), StoreError>
Provides an initial state of a certain type to the store.
§Arguments
initial_state- The initial state to be held in the store.
§Returns
A Result indicating success or failure.
§Examples
use sovran_state::{Store, State, StoreError};
#[derive(Clone, Debug)]
struct MyState {
value: i32,
}
impl State for MyState {}
let store = Store::new();
match store.provide(MyState { value: 20 }) {
Ok(_) => println!("State provided successfully"),
Err(err) => println!("Failed to provide state: {:?}", err),
}Examples found in repository?
examples/sovran_example.rs (lines 82-85)
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
fn main() {
// Create store and provide initial state
let store = Arc::new(Store::new());
store.provide(BankState {
balance: 1000.0,
transaction_count: 0,
}).expect("Failed to provide initial state");
// Create our components
let monitor = AccountMonitor::new(store.clone());
let _logger = TransactionLogger::new(store.clone());
println!("Initial balance: ${:.2}", monitor.check_balance());
// Simulate some transactions
println!("\nProcessing transactions...\n");
// Deposit
store.dispatch(DepositAction(500.0))
.expect("Failed to process deposit");
thread::sleep(Duration::from_millis(500));
// Withdraw
store.dispatch(WithdrawAction(200.0))
.expect("Failed to process withdrawal");
thread::sleep(Duration::from_millis(500));
// Deposit again
store.dispatch(DepositAction(750.0))
.expect("Failed to process deposit");
thread::sleep(Duration::from_millis(500));
println!("\nFinal balance: ${:.2}", monitor.check_balance());
}Sourcepub fn get_state<S: State>(&self) -> Result<S, StoreError>
pub fn get_state<S: State>(&self) -> Result<S, StoreError>
Retrieves the current state of a given type.
§Returns
A Result containing the state on success, or a StoreError on failure.
§Examples
use sovran_state::{Store, State, StoreError};
#[derive(Clone, Debug)]
struct MyState {
value: i32,
}
impl State for MyState {}
let store = Store::new();
store.provide(MyState { value: 20 }).unwrap();
match store.get_state::<MyState>() {
Ok(state) => println!("State value: {}", state.value),
Err(err) => println!("Failed to get state: {:?}", err),
}Sourcepub fn dispatch<S: State, A: Action<S> + Send + 'static>(
&self,
action: A,
) -> Result<(), StoreError>
pub fn dispatch<S: State, A: Action<S> + Send + 'static>( &self, action: A, ) -> Result<(), StoreError>
Dispatches an action to the store, affecting the state of a specific type.
§Arguments
action- An action that transforms the state.
§Returns
A Result indicating success or failure.
§Examples
use sovran_state::{Store, State, Action, StoreError};
#[derive(Clone, Debug)]
struct MyState {
value: i32,
}
impl State for MyState {}
struct IncrementAction;
impl Action<MyState> for IncrementAction {
fn reduce(&self, state: MyState) -> MyState {
MyState { value: state.value + 1 }
}
}
let store = Store::new();
store.provide(MyState { value: 0 }).unwrap();
match store.dispatch(IncrementAction) {
Ok(_) => println!("Action dispatched successfully"),
Err(err) => println!("Failed to dispatch action: {:?}", err),
}Examples found in repository?
examples/sovran_example.rs (line 97)
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
fn main() {
// Create store and provide initial state
let store = Arc::new(Store::new());
store.provide(BankState {
balance: 1000.0,
transaction_count: 0,
}).expect("Failed to provide initial state");
// Create our components
let monitor = AccountMonitor::new(store.clone());
let _logger = TransactionLogger::new(store.clone());
println!("Initial balance: ${:.2}", monitor.check_balance());
// Simulate some transactions
println!("\nProcessing transactions...\n");
// Deposit
store.dispatch(DepositAction(500.0))
.expect("Failed to process deposit");
thread::sleep(Duration::from_millis(500));
// Withdraw
store.dispatch(WithdrawAction(200.0))
.expect("Failed to process withdrawal");
thread::sleep(Duration::from_millis(500));
// Deposit again
store.dispatch(DepositAction(750.0))
.expect("Failed to process deposit");
thread::sleep(Duration::from_millis(500));
println!("\nFinal balance: ${:.2}", monitor.check_balance());
}Sourcepub fn subscribe<S: State, F: Fn(&S) + Send + Sync + 'static>(
&self,
callback: F,
) -> Result<SubscriberId, StoreError>
pub fn subscribe<S: State, F: Fn(&S) + Send + Sync + 'static>( &self, callback: F, ) -> Result<SubscriberId, StoreError>
Subscribes to state changes of a specific type with a given callback.
§Arguments
callback- A callback function that will be invoked when the state changes.
§Returns
A Result containing the subscriber ID on success, or a StoreError on failure.
§Examples
use sovran_state::{Store, State, StoreError};
#[derive(Clone, Debug)]
struct MyState {
value: i32,
}
impl State for MyState {}
let store = Store::new();
store.provide(MyState { value: 10 }).unwrap();
match store.subscribe(|state: &MyState| {
println!("State changed: {:?}", state);
}) {
Ok(subscriber_id) => println!("Subscribed with ID: {}", subscriber_id),
Err(err) => println!("Failed to subscribe: {:?}", err),
}Examples found in repository?
examples/sovran_example.rs (lines 51-53)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
fn new(store: Arc<Store>) -> Self {
let monitor = AccountMonitor { store: store.clone() };
// Subscribe to state changes
monitor.store.subscribe(move |state: &BankState| {
println!("🏦 Account Monitor: Balance changed to ${:.2}", state.balance);
}).expect("Failed to subscribe to state changes");
monitor
}
fn check_balance(&self) -> f64 {
self.store.get_state::<BankState>()
.map(|state| state.balance)
.unwrap_or(0.0)
}
}
impl TransactionLogger {
fn new(store: Arc<Store>) -> Self {
let logger = TransactionLogger { store: store.clone() };
// Subscribe to state changes
logger.store.subscribe(move |state: &BankState| {
println!("📝 Transaction Logger: Transaction #{} processed",
state.transaction_count);
}).expect("Failed to subscribe to state changes");
logger
}Sourcepub fn unsubscribe<S: State>(&self, id: SubscriberId) -> Result<(), StoreError>
pub fn unsubscribe<S: State>(&self, id: SubscriberId) -> Result<(), StoreError>
Unsubscribes from state changes of a specific type using the given subscriber ID.
§Arguments
id- The ID of the subscriber to be removed.
§Returns
A Result indicating success or failure.
§Examples
use sovran_state::{Store, State, StoreError};
#[derive(Clone, Debug)]
struct MyState {
value: i32,
}
impl State for MyState {}
let store = Store::new();
store.provide(MyState { value: 10 }).unwrap();
let id = store.subscribe(|state: &MyState| {
println!("State changed: {:?}", state);
}).unwrap();
match store.unsubscribe::<MyState>(id) {
Ok(_) => println!("Unsubscribed successfully"),
Err(err) => println!("Failed to unsubscribe: {:?}", err),
}Trait Implementations§
Auto Trait Implementations§
impl Freeze for Store
impl RefUnwindSafe for Store
impl Send for Store
impl Sync for Store
impl Unpin for Store
impl UnwindSafe for Store
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
🔬This is a nightly-only experimental API. (
clone_to_uninit)