Expand description
Shared state container for inter-window communication.
This module provides the SharedContext type for sharing state across
multiple views in a Dampen application.
§Overview
SharedContext<S> is a thread-safe, reference-counted container that allows
multiple views to read and write a shared state. When one view modifies the
shared state, all other views immediately see the change.
§Example
use dampen_core::SharedContext;
use dampen_core::UiBindable;
use dampen_core::BindingValue;
#[derive(Default, Clone)]
struct SharedState {
theme: String,
language: String,
}
impl UiBindable for SharedState {
fn get_field(&self, path: &[&str]) -> Option<BindingValue> {
match path {
["theme"] => Some(BindingValue::String(self.theme.clone())),
["language"] => Some(BindingValue::String(self.language.clone())),
_ => None,
}
}
fn available_fields() -> Vec<String> {
vec!["theme".to_string(), "language".to_string()]
}
}
// Create shared context
let ctx = SharedContext::new(SharedState::default());
// Clone for another view (same underlying state)
let ctx2 = ctx.clone();
// Modify in one view
ctx.write().theme = "dark".to_string();
// See change in another view
assert_eq!(ctx2.read().theme, "dark");§Thread Safety
SharedContext uses Arc<RwLock<S>> internally, making it safe to share
across threads. Multiple readers can access the state simultaneously, but
writers get exclusive access.
§See Also
AppState- Per-view state container that can hold aSharedContextUiBindable- Trait required for shared state types
Structs§
- Shared
Context - Thread-safe shared state container.