gpui-global
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOverview
概述
Global state in GPUI provides app-wide shared data accessible from any context.
Key Trait: - Implement on types to make them globally accessible
GlobalGPUI中的全局状态提供了可从任何上下文访问的应用级共享数据。
核心特性: - 在类型上实现该特性以使其可全局访问
GlobalQuick Start
快速开始
Define Global State
定义全局状态
rust
use gpui::Global;
#[derive(Clone)]
struct AppSettings {
theme: Theme,
language: String,
}
impl Global for AppSettings {}rust
use gpui::Global;
#[derive(Clone)]
struct AppSettings {
theme: Theme,
language: String,
}
impl Global for AppSettings {}Set and Access Globals
设置与访问全局状态
rust
fn main() {
let app = Application::new();
app.run(|cx: &mut App| {
// Set global
cx.set_global(AppSettings {
theme: Theme::Dark,
language: "en".to_string(),
});
// Access global (read-only)
let settings = cx.global::<AppSettings>();
println!("Theme: {:?}", settings.theme);
});
}rust
fn main() {
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>();
println!("Theme: {:?}", settings.theme);
});
}Update Globals
更新全局状态
rust
impl MyComponent {
fn change_theme(&mut self, new_theme: Theme, cx: &mut Context<Self>) {
cx.update_global::<AppSettings, _>(|settings, cx| {
settings.theme = new_theme;
// Global updates don't trigger automatic notifications
// Manually notify components that care
});
cx.notify(); // Re-render this component
}
}rust
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(); // 重新渲染当前组件
}
}Common Use Cases
常见使用场景
1. App Configuration
1. 应用配置
rust
#[derive(Clone)]
struct AppConfig {
api_endpoint: String,
max_retries: u32,
timeout: Duration,
}
impl Global for AppConfig {}
// Set once at startup
cx.set_global(AppConfig {
api_endpoint: "https://api.example.com".to_string(),
max_retries: 3,
timeout: Duration::from_secs(30),
});
// Access anywhere
let config = cx.global::<AppConfig>();rust
#[derive(Clone)]
struct AppConfig {
api_endpoint: String,
max_retries: u32,
timeout: Duration,
}
impl Global for AppConfig {}
// 在启动时一次性设置
cx.set_global(AppConfig {
api_endpoint: "https://api.example.com".to_string(),
max_retries: 3,
timeout: Duration::from_secs(30),
});
// 在任意位置访问
let config = cx.global::<AppConfig>();2. Feature Flags
2. 功能开关
rust
#[derive(Clone)]
struct FeatureFlags {
enable_beta_features: bool,
enable_analytics: bool,
}
impl Global for FeatureFlags {}
impl MyComponent {
fn render_beta_feature(&self, cx: &App) -> Option<impl IntoElement> {
let flags = cx.global::<FeatureFlags>();
if flags.enable_beta_features {
Some(div().child("Beta feature"))
} else {
None
}
}
}rust
#[derive(Clone)]
struct FeatureFlags {
enable_beta_features: bool,
enable_analytics: bool,
}
impl Global for FeatureFlags {}
impl MyComponent {
fn render_beta_feature(&self, cx: &App) -> Option<impl IntoElement> {
let flags = cx.global::<FeatureFlags>();
if flags.enable_beta_features {
Some(div().child("Beta功能"))
} else {
None
}
}
}3. Shared Services
3. 共享服务
rust
#[derive(Clone)]
struct ServiceRegistry {
http_client: Arc<HttpClient>,
logger: Arc<Logger>,
}
impl Global for ServiceRegistry {}
impl MyComponent {
fn fetch_data(&mut self, cx: &mut Context<Self>) {
let registry = cx.global::<ServiceRegistry>();
let client = registry.http_client.clone();
cx.spawn(async move |cx| {
let data = client.get("api/data").await?;
// Process data...
Ok::<_, anyhow::Error>(())
}).detach();
}
}rust
#[derive(Clone)]
struct ServiceRegistry {
http_client: Arc<HttpClient>,
logger: Arc<Logger>,
}
impl Global for ServiceRegistry {}
impl MyComponent {
fn fetch_data(&mut self, cx: &mut Context<Self>) {
let registry = cx.global::<ServiceRegistry>();
let client = registry.http_client.clone();
cx.spawn(async move |cx| {
let data = client.get("api/data").await?;
// 处理数据...
Ok::<_, anyhow::Error>(())
}).detach();
}
}Best Practices
最佳实践
✅ Use Arc for Shared Resources
✅ 对共享资源使用Arc
rust
#[derive(Clone)]
struct GlobalState {
database: Arc<Database>, // Cheap to clone
cache: Arc<RwLock<Cache>>,
}
impl Global for GlobalState {}rust
#[derive(Clone)]
struct GlobalState {
database: Arc<Database>, // 克隆成本低
cache: Arc<RwLock<Cache>>,
}
impl Global for GlobalState {}✅ Immutable by Default
✅ 默认使用不可变状态
Globals are read-only by default. Use interior mutability when needed:
rust
#[derive(Clone)]
struct Counter {
count: Arc<AtomicUsize>,
}
impl Global for Counter {}
impl Counter {
fn increment(&self) {
self.count.fetch_add(1, Ordering::SeqCst);
}
fn get(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
}全局状态默认是只读的。需要时使用内部可变性:
rust
#[derive(Clone)]
struct Counter {
count: Arc<AtomicUsize>,
}
impl Global for Counter {}
impl Counter {
fn increment(&self) {
self.count.fetch_add(1, Ordering::SeqCst);
}
fn get(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
}❌ Don't: Overuse Globals
❌ 避免:过度使用全局状态
rust
// ❌ Bad: Too many globals
cx.set_global(UserState { ... });
cx.set_global(CartState { ... });
cx.set_global(CheckoutState { ... });
// ✅ Good: Use entities for component state
let user_entity = cx.new(|_| UserState { ... });rust
// ❌ 不良示例:全局状态过多
cx.set_global(UserState { ... });
cx.set_global(CartState { ... });
cx.set_global(CheckoutState { ... });
// ✅ 良好示例:使用实体存储组件状态
let user_entity = cx.new(|_| UserState { ... });When to Use
使用场景对比
Use Globals for:
- App-wide configuration
- Feature flags
- Shared services (HTTP client, logger)
- Read-only reference data
Use Entities for:
- Component-specific state
- State that changes frequently
- State that needs notifications
适合使用全局状态的场景:
- 应用级配置
- 功能开关
- 共享服务(HTTP客户端、日志器)
- 只读参考数据
适合使用实体的场景:
- 组件专属状态
- 频繁变更的状态
- 需要自动通知的状态
Reference Documentation
参考文档
- API Reference: See api-reference.md
- Global trait, set_global, update_global
- Interior mutability patterns
- Best practices and anti-patterns
- API参考:查看 api-reference.md
- Global特性、set_global、update_global
- 内部可变性模式
- 最佳实践与反模式