What problem does it solve?
Global state management in GPUI provides a centralized mechanism to share app-wide data across components.
Core Features & Use Cases
- Define and register global state types by implementing the Global trait.
- Set, access, and update globals from anywhere in the app using cx.set_global, cx.global, and cx.update_global.
- Support immutable reads with easy mutation via interior mutability patterns, and notify components when needed.
Quick Start
The following example shows how to declare a global state type, register it, and use it.
Define a global state
use gpui::Global;
#[derive(Clone)]
struct AppSettings {
theme: Theme,
language: String,
}
impl Global for AppSettings {}
Set global at startup
let app = Application::new();
app.run(|cx: &mut App| {
cx.set_global(AppSettings {
theme: Theme::Dark,
language: "en".to_string(),
});
let settings = cx.global::<AppSettings>();
});
Update global example
impl MyComponent {
fn change_theme(&mut self, new_theme: Theme, cx: &mut Context<Self>) {
cx.update_global::<AppSettings, _>(|settings, cx| {
settings.theme = new_theme;
});
cx.notify();
}
}