Observable-Property
Features
- Thread-safe: Uses
Arc<RwLock<>>for safe concurrent access - Observer pattern: Subscribe to property changes with callbacks
- RAII subscriptions: Automatic cleanup with subscription guards (no manual unsubscribe needed)
- Filtered observers: Only notify when specific conditions are met
- Computed properties: Automatically recompute derived values when dependencies change
- Debouncing: Delay notifications until changes stop for a specified duration
- Throttling: Rate-limit notifications to at most once per time interval
- Async notifications: Non-blocking observer notifications with background threads
- Configurable threading: Customize thread pool size for async notifications via
with_max_threads() - Panic isolation: Observer panics don't crash the system
- Robust error handling: Comprehensive error handling with descriptive error messages
- Production-ready: No
unwrap()calls - all errors are handled gracefully - Type-safe: Generic implementation works with any `Clone + Send + Sync + 'static' type
- Zero dependencies: Uses only Rust standard library
- Exhaustively tested: 235 tests (128 unit + 107 doc tests) with 100% feature coverage
A thread-safe observable property implementation for Rust that allows you to observe changes to values across multiple threads. Built with comprehensive error handling and no unwrap() calls for maximum reliability.
Contact me
If you find bugs, please mail me at snoekiede@gmail.com and mention the name of the crate in the subject.
Quick Start
Add this to your Cargo.toml:
[]
= "0.4.2"
Usage
Basic Example
use ObservableProperty;
use Arc;
Multi-threading Example
use ObservableProperty;
use Arc;
use thread;
Filtered Observers
use ObservableProperty;
use Arc;
RAII Subscriptions (Recommended)
For automatic cleanup without manual unsubscribe calls, use RAII subscriptions:
use ObservableProperty;
use Arc;
Filtered RAII Subscriptions
Combine filtering with automatic cleanup:
use ObservableProperty;
use Arc;
Computed Properties
Computed properties automatically update when their dependencies change. Perfect for derived values:
use ;
use Arc;
Debouncing
Debouncing delays notifications until changes stop for a specified duration. Perfect for auto-save, search-as-you-type, and form validation:
use ObservableProperty;
use Arc;
use Duration;
Throttling
Throttling rate-limits notifications to at most once per interval. Perfect for scroll events, mouse tracking, and API rate limiting:
use ObservableProperty;
use Arc;
use Duration;
Key Differences:
- Debouncing: Waits for changes to stop, then notifies once with the final value
- Throttling: Notifies periodically during continuous changes, firing first immediately
Async Notifications
For observers that might perform time-consuming operations, use async notifications to avoid blocking:
use ObservableProperty;
use Arc;
use Duration;
Configurable Threading
Customize the thread pool size for async notifications based on your system requirements:
use ObservableProperty;
use Arc;
Error Handling
The library uses a comprehensive error system for robust, production-ready error handling. All operations are designed to fail gracefully with meaningful error messages - there are no unwrap() calls that can cause unexpected panics.
Error Types
The library provides detailed error information through the PropertyError enum:
use ;
use Arc;
Graceful Degradation
The library is designed to handle edge cases gracefully:
- Poisoned locks: When a thread panics while holding a lock, the property becomes "poisoned." All subsequent operations return clear error messages instead of panicking
- Observer panics: If an observer function panics, it's isolated - other observers continue to work normally
- Thread safety: All error conditions are thread-safe and don't cause data races or undefined behavior
- Resource cleanup: RAII subscriptions clean up properly even when locks are poisoned or other errors occur
// Even if a lock is poisoned, operations fail gracefully
match property.subscribe_with_subscription
Subscription Management
The library provides two approaches for managing observer subscriptions:
Manual Management
let observer_id = property.subscribe?;
// ... use the property
property.unsubscribe?; // Manual cleanup required
RAII Management (Recommended)
let _subscription = property.subscribe_with_subscription?;
// ... use the property
// Automatic cleanup when _subscription goes out of scope
Benefits of RAII subscriptions:
- ✅ No manual cleanup required
- ✅ Exception-safe (cleanup happens even if code panics)
- ✅ Works across thread boundaries
- ✅ Prevents observer leaks in complex control flow
Performance Considerations
- Observers: Each observer is called sequentially. For heavy computations, use
set_async()to run observers in background threads. - Lock contention: The property uses a single
RwLockinternally. Consider having fewer, larger properties rather than many small ones. - Memory: Observer functions are stored as
Arc<dyn Fn>and kept until unsubscribed or subscription is dropped. - RAII overhead: Subscription objects have minimal overhead (just an ID and Arc reference).
Thread Safety
All operations are thread-safe with comprehensive error handling:
- Multiple threads can read the property value simultaneously
- Only one thread can modify the property at a time
- Observer notifications happen outside the lock to minimize contention
- Observer panics are isolated and don't affect other observers or the property
- RAII subscriptions can be created and dropped from any thread
- Poisoned locks are handled gracefully - subscriptions clean up without panicking
- No
unwrap()calls - all potential failure points use proper error handling - Fail-safe design - errors never cause undefined behavior or crashes
Best Practices
Use RAII Subscriptions
Prefer subscribe_with_subscription() and subscribe_filtered_with_subscription() over manual subscription management:
// ✅ Recommended: RAII subscription
let _subscription = property.subscribe_with_subscription?;
// Automatically cleaned up
// ❌ Discouraged: Manual management (error-prone)
let id = property.subscribe?;
property.unsubscribe?; // Easy to forget or miss in error paths
Scoped Subscriptions
Use block scoping for temporary subscriptions:
// No more monitoring
Lightweight Observers
Keep observer functions lightweight for better performance:
// ✅ Good: Lightweight observer
let _subscription = property.subscribe_with_subscription?;
// ❌ Avoid: Heavy computation in observer
let _subscription = property.subscribe_with_subscription?;
// ✅ Better: Use async for heavy work
property.set_async?; // Non-blocking
Comprehensive Error Handling
The library is production-ready with robust error handling. Always handle potential errors:
Key benefits:
- ✅ No
unwrap()calls that could panic unexpectedly - ✅ Clear, descriptive error messages for debugging
- ✅ Graceful degradation in all error conditions
- ✅ Thread-safe error handling
match property.subscribe_with_subscription
Migration from Manual to RAII Subscriptions
If you're upgrading from manual subscription management:
// Before (manual management)
let observer_id = property.subscribe?;
// ... do work
property.unsubscribe?;
// After (RAII management)
let _subscription = property.subscribe_with_subscription?;
// ... do work
// Automatic cleanup!
Recent Improvements
v0.4.1 - Debouncing & Throttling
- ⏱️ Debouncing support: New
subscribe_debounced()delays notifications until changes stop - 🎯 Throttling support: New
subscribe_throttled()rate-limits notifications to maximum frequency - 🔍 Perfect for UX: Auto-save, search-as-you-type, form validation, scroll handlers
- 📈 Performance optimization: Reduce unnecessary observer calls during rapid changes
- 🧪 Comprehensive tests: 13 new tests covering debouncing and throttling behavior
- 📚 Rich documentation: Detailed examples for auto-save, search, scroll events, and more
- 🔒 Thread-safe: Both features work seamlessly in multi-threaded environments
v0.4.2 - Exhaustive Test Coverage
- 🧪 Exhaustive test suite: 235 total tests (128 unit tests + 107 doc tests) with 100% feature coverage
- ✅ All features tested: Comprehensive tests for validation, custom equality, history, event logging, transformations, bidirectional binding, metrics, persistence, and async features
- 🎯 Production confidence: Every public API thoroughly tested with both happy paths and error conditions
- 📊 Quality assurance: All tests passing, ensuring reliability and correctness
- 🔍 Edge cases covered: Tests include concurrent access, error handling, thread safety, and resource limits
v0.3.2 - Configurable Threading & Enhanced Documentation
- ⚙️ Configurable thread pools: New
with_max_threads()constructor allows custom thread limits for async notifications - 📖 Comprehensive documentation: Complete API documentation with examples, use cases, and performance guidance
- 🧪 Expanded test coverage: Foundation for exhaustive testing with unit and documentation tests
- 🎯 Performance tuning: Fine-tune async notification performance for different system requirements
- 🔧 Better async control: Optimize for CPU-bound, I/O-bound, or resource-constrained environments
- 📚 Rich examples: Detailed code examples for high-throughput, embedded, and network-heavy scenarios
v0.2.1 - Enhanced Error Handling & Production Readiness
- 🔧 Eliminated all
unwrap()calls: Replaced with proper error handling usingexpect()with descriptive messages - 🛡️ Enhanced robustness: All error conditions now provide clear, actionable error messages
- 🧪 Improved testing: Foundation for comprehensive test suite ensuring reliability
- 🔒 Better poisoned lock handling: Graceful degradation when locks are poisoned by panics
- 📈 Production ready: Suitable for production environments with comprehensive error handling
- 🚀 Performance: No runtime performance impact from improved error handling
- 📚 Better debugging: Clear error context helps identify issues quickly
The library now provides both robust error handling and configurable performance tuning, making it suitable for a wide range of production environments from embedded systems to high-throughput servers.
Testing
This library has exhaustive test coverage with 235 total tests ensuring reliability and correctness:
Test Statistics
- 128 unit tests - Comprehensive testing of all functionality
- 107 documentation tests - Every public API example is tested
- 100% passing - All tests consistently pass
Coverage Areas
Core Features (100% Covered)
- ✅ Property creation and basic operations
- ✅ Observer subscription and notification
- ✅ RAII subscription automatic cleanup
- ✅ Thread safety and concurrent access
- ✅ Error handling and graceful degradation
- ✅ Async notifications with background threads
Advanced Features (100% Covered)
- ✅ Validation (
with_validator) - Valid/invalid values, error handling - ✅ Custom Equality (
with_equality) - Epsilon tolerance, case-insensitive strings - ✅ History Tracking (
with_history) - Undo/redo, bounded buffers - ✅ Event Logging (
with_event_log) - Complete audit trails with timestamps - ✅ Property Transformations (
map) - Type conversions, chaining - ✅ Atomic Modifications (
modify) - With validators, complex updates - ✅ Bidirectional Binding - Two-way sync, loop prevention
- ✅ Performance Metrics - Observer call counts, notification timing
- ✅ Persistence - Load/save, auto-save on changes
- ✅ Filtering - Conditional observers with predicates
- ✅ Debouncing & Throttling - Rate limiting, delay notifications
- ✅ Computed Properties - Automatic dependency tracking
Edge Cases & Error Conditions
- ✅ Lock poisoning recovery
- ✅ Observer panics isolation
- ✅ Observer limit enforcement
- ✅ Concurrent subscription management
- ✅ Weak observer cleanup
- ✅ Empty history/event log handling
- ✅ Invalid initial values
- ✅ Thread ID wraparound
Running Tests
# Run all tests (unit + doc tests)
# Run only unit tests
# Run only documentation tests
# Run with output
All tests complete in ~7 seconds and demonstrate both correct behavior and robust error handling.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Disclaimer
This software is provided "as-is" without any express or implied warranties. While every effort has been made to ensure reliability and correctness, the authors and contributors make no guarantees regarding the software's performance, suitability for any particular purpose, or freedom from defects. Use this library at your own risk.
Users are responsible for:
- Testing the library thoroughly in their specific use cases
- Implementing appropriate error handling and validation
- Ensuring the library meets their performance and reliability requirements
The comprehensive error handling and extensive test suite are designed to promote reliability, but do not constitute a warranty or guarantee of correctness.
License
This project is licensed under either the:
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.