State
State in Lokey is shared runtime data stored in the device Context.
Components use state to coordinate behavior without needing direct references to each other.
At the type level, Lokey provides three main access patterns:
AnyStatefor type-erased lookup by typeState<T>for direct typed access to a specific stored typeQueryState<T>for query-based access when callers should not depend on the exact stored type
These types can be implemented for a struct using the State derive macro.
See the state module for the complete API reference.
Accessing state
When the concrete state type is not known, use AnyState::try_get:
let my_value = context.state.try_get::<MyValue>()?;When the concrete state type is known, use State<T>::get:
use lokey::State;
let my_value = State::<MyValue>::get(context.state);State queries
Queries are useful when callers should depend on a lightweight view instead of the exact stored type.
This is especially helpful for generic state entries. For example, LayerManager has const generics, but keyboard actions typically only need a stable query interface. In that case, the caller can work with LayerManagerQuery instead of the exact LayerManager<N> type.
To make a field queryable:
- Implement
ToStateQueryfor the stored type. - Mark the field with
#[state(query)]. - Access it via
AnyState::try_queryorQueryState::query.
use lokey::State;
use lokey_layer::{LayerManager, LayerManagerQuery};
#[derive(Default, State)]
struct MyState {
#[state(query)]
layer_manager: LayerManager<0>,
}
let layer_manager = context.state.try_query::<LayerManagerQuery>()?;