Event Bus Usage
OneClaw’s event bus provides pub/sub messaging for reactive event processing. Two implementations are available: DefaultEventBus (synchronous, drain-based) and AsyncEventBus (real-time, tokio-based).Event Bus Overview
The event bus acts as the “nervous system” of OneClaw, enabling:- Decoupled components: Publishers don’t know about subscribers
- Event pipelines: Chain handlers to create processing workflows
- Real-time reactions: Respond to sensor data, alerts, state changes
- Event history: Replay recent events for debugging
Event Structure
DefaultEventBus (Sync)
The default, drain-based event bus for synchronous event processing.Creating the Bus
Publishing Events
Subscribing to Events
Draining Events
Unsubscribing
AsyncEventBus (Real-time)
Tokio-based event bus for real-time event processing without drain loops.Creating the Async Bus
Publishing (Immediate Processing)
Async Channel Subscription
Multiple Async Receivers
Sync Subscriptions (EventBus trait compat)
Event Pipelines
Chain handlers to create processing workflows.Example: Alert Pipeline
Multi-Stage Pipeline
Real-Time Event Processing
AsyncEventBus processes events immediately without drain loops.Example: Live Sensor Monitoring
Latency Test
From the test suite:Event History
Retrieving Recent Events
History Ring Buffer
Choosing the Right Bus
Use DefaultEventBus when:
- Running in sync context (no tokio runtime)
- Want explicit control over event processing (drain loops)
- Building batch processing systems
- Need deterministic event ordering
- Working with simple CLI tools
Use AsyncEventBus when:
- Running in async context (tokio runtime)
- Need real-time event processing
- Building websocket servers, IoT dashboards
- Want concurrent event consumers
- Processing high-throughput event streams
Sync vs Async Comparison
| Feature | DefaultEventBus | AsyncEventBus |
|---|---|---|
| Processing | Drain-based | Immediate |
| Runtime | Sync | Tokio |
| Concurrency | Single-threaded drain | Multi-receiver broadcast |
| Latency | Drain interval | <10ms |
| Use case | CLI, batch jobs | Real-time, IoT |
| drain() | Processes events | No-op |
| pending_count() | Queue size | Always 0 |
Best Practices
- Use topic hierarchies:
sensor.temperature.living_roomis better thansensor_temp_lr - Set appropriate priorities: Critical = immediate action, High = important, Normal = info
- Keep handlers fast: Long-running handlers block event processing
- Avoid infinite loops: Don’t publish events that trigger the same handler
- Use event history for debugging: Check
recent_events()when things go wrong - Clean up subscriptions: Call
unsubscribe()when handlers are no longer needed - Monitor history size: Tune
with_max_history()based on your needs
EventBus Trait
Both implementations satisfy this trait:See Also
- Architecture - Event bus layer design
- API Reference - Full trait documentation
- Custom Tools Guide - Build tools that emit events