Expand description
§Observable Property
A thread-safe observable property implementation for Rust that allows you to observe changes to values across multiple threads.
§Features
- Thread-safe: Uses
Arc<RwLock<>>for safe concurrent access - Observer pattern: Subscribe to property changes with callbacks
- Filtered observers: Only notify when specific conditions are met
- Async notifications: Non-blocking observer notifications with background threads
- Panic isolation: Observer panics don’t crash the system
- Type-safe: Generic implementation works with any
Clone + Send + Synctype
§Quick Start
use observable_property::ObservableProperty;
use std::sync::Arc;
// Create an observable property
let property = ObservableProperty::new(42);
// Subscribe to changes
let observer_id = match property.subscribe(Arc::new(|old_value, new_value| {
println!("Value changed from {} to {}", old_value, new_value);
})) {
Ok(id) => id,
Err(e) => {
eprintln!("Failed to subscribe observer: {}", e);
return; // or handle error appropriately
}
};
// Change the value (triggers observer)
if let Err(e) = property.set(100) {
eprintln!("Failed to set property value: {}", e);
return; // or handle error appropriately
}
// Unsubscribe when done
match property.unsubscribe(observer_id) {
Ok(_) => println!("Observer unsubscribed successfully"),
Err(e) => eprintln!("Failed to unsubscribe observer: {}", e),
}§Multi-threading Example
use observable_property::ObservableProperty;
use std::sync::Arc;
use std::thread;
let property = Arc::new(ObservableProperty::new(0));
let property_clone = property.clone();
// Subscribe from one thread
match property.subscribe(Arc::new(|old, new| {
println!("Value changed: {} -> {}", old, new);
})) {
Ok(_) => println!("Observer subscribed successfully"),
Err(e) => {
eprintln!("Failed to subscribe observer: {}", e);
return; // or handle error appropriately
}
};
// Modify from another thread
match thread::spawn(move || {
if let Err(e) = property_clone.set(42) {
eprintln!("Failed to set property value: {}", e);
}
}).join() {
Ok(_) => println!("Thread completed successfully"),
Err(e) => eprintln!("Thread panicked: {:?}", e),
};Structs§
- Observable
Property - A thread-safe observable property that notifies observers when its value changes
Enums§
- Property
Error - Errors that can occur when working with ObservableProperty
Type Aliases§
- Observer
- Function type for observers that get called when property values change
- Observer
Id - Unique identifier for registered observers