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?
79fn main() {
80 // Create store and provide initial state
81 let store = Arc::new(Store::new());
82 store.provide(BankState {
83 balance: 1000.0,
84 transaction_count: 0,
85 }).expect("Failed to provide initial state");
86
87 // Create our components
88 let monitor = AccountMonitor::new(store.clone());
89 let _logger = TransactionLogger::new(store.clone());
90
91 println!("Initial balance: ${:.2}", monitor.check_balance());
92
93 // Simulate some transactions
94 println!("\nProcessing transactions...\n");
95
96 // Deposit
97 store.dispatch(DepositAction(500.0))
98 .expect("Failed to process deposit");
99 thread::sleep(Duration::from_millis(500));
100
101 // Withdraw
102 store.dispatch(WithdrawAction(200.0))
103 .expect("Failed to process withdrawal");
104 thread::sleep(Duration::from_millis(500));
105
106 // Deposit again
107 store.dispatch(DepositAction(750.0))
108 .expect("Failed to process deposit");
109 thread::sleep(Duration::from_millis(500));
110
111 println!("\nFinal balance: ${:.2}", monitor.check_balance());
112}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?
79fn main() {
80 // Create store and provide initial state
81 let store = Arc::new(Store::new());
82 store.provide(BankState {
83 balance: 1000.0,
84 transaction_count: 0,
85 }).expect("Failed to provide initial state");
86
87 // Create our components
88 let monitor = AccountMonitor::new(store.clone());
89 let _logger = TransactionLogger::new(store.clone());
90
91 println!("Initial balance: ${:.2}", monitor.check_balance());
92
93 // Simulate some transactions
94 println!("\nProcessing transactions...\n");
95
96 // Deposit
97 store.dispatch(DepositAction(500.0))
98 .expect("Failed to process deposit");
99 thread::sleep(Duration::from_millis(500));
100
101 // Withdraw
102 store.dispatch(WithdrawAction(200.0))
103 .expect("Failed to process withdrawal");
104 thread::sleep(Duration::from_millis(500));
105
106 // Deposit again
107 store.dispatch(DepositAction(750.0))
108 .expect("Failed to process deposit");
109 thread::sleep(Duration::from_millis(500));
110
111 println!("\nFinal balance: ${:.2}", monitor.check_balance());
112}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?
79fn main() {
80 // Create store and provide initial state
81 let store = Arc::new(Store::new());
82 store.provide(BankState {
83 balance: 1000.0,
84 transaction_count: 0,
85 }).expect("Failed to provide initial state");
86
87 // Create our components
88 let monitor = AccountMonitor::new(store.clone());
89 let _logger = TransactionLogger::new(store.clone());
90
91 println!("Initial balance: ${:.2}", monitor.check_balance());
92
93 // Simulate some transactions
94 println!("\nProcessing transactions...\n");
95
96 // Deposit
97 store.dispatch(DepositAction(500.0))
98 .expect("Failed to process deposit");
99 thread::sleep(Duration::from_millis(500));
100
101 // Withdraw
102 store.dispatch(WithdrawAction(200.0))
103 .expect("Failed to process withdrawal");
104 thread::sleep(Duration::from_millis(500));
105
106 // Deposit again
107 store.dispatch(DepositAction(750.0))
108 .expect("Failed to process deposit");
109 thread::sleep(Duration::from_millis(500));
110
111 println!("\nFinal balance: ${:.2}", monitor.check_balance());
112}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. The callback will receive the current state of the type immediately.
§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?
47 fn new(store: Arc<Store>) -> Self {
48 let monitor = AccountMonitor { store: store.clone() };
49
50 // Subscribe to state changes
51 monitor.store.subscribe(move |state: &BankState| {
52 println!("🏦 Account Monitor: Balance changed to ${:.2}", state.balance);
53 }).expect("Failed to subscribe to state changes");
54
55 monitor
56 }
57
58 fn check_balance(&self) -> f64 {
59 self.store.get_state::<BankState>()
60 .map(|state| state.balance)
61 .unwrap_or(0.0)
62 }
63}
64
65impl TransactionLogger {
66 fn new(store: Arc<Store>) -> Self {
67 let logger = TransactionLogger { store: store.clone() };
68
69 // Subscribe to state changes
70 logger.store.subscribe(move |state: &BankState| {
71 println!("📝 Transaction Logger: Transaction #{} processed",
72 state.transaction_count);
73 }).expect("Failed to subscribe to state changes");
74
75 logger
76 }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),
}