gpui-entity
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOverview
概述
An is a handle to state of type , providing safe access and updates.
Entity<T>TKey Methods:
- →
entity.read(cx)- Read-only access&T - →
entity.read_with(cx, |state, cx| ...)- Read with closureR - →
entity.update(cx, |state, cx| ...)- Mutable updateR - →
entity.downgrade()- Create weak referenceWeakEntity<T> - →
entity.entity_id()- Unique identifierEntityId
Entity Types:
- : Strong reference (increases ref count)
Entity<T> - : Weak reference (doesn't prevent cleanup, returns
WeakEntity<T>)Result
Entity<T>T核心方法:
- →
entity.read(cx)- 只读访问&T - →
entity.read_with(cx, |state, cx| ...)- 通过闭包读取R - →
entity.update(cx, |state, cx| ...)- 可变更新R - →
entity.downgrade()- 创建弱引用WeakEntity<T> - →
entity.entity_id()- 唯一标识符EntityId
实体类型:
- :强引用(增加引用计数)
Entity<T> - :弱引用(不会阻止资源回收,返回
WeakEntity<T>)Result
Quick Start
快速入门
Creating and Using Entities
创建与使用实体
rust
// Create entity
let counter = cx.new(|cx| Counter { count: 0 });
// Read state
let count = counter.read(cx).count;
// Update state
counter.update(cx, |state, cx| {
state.count += 1;
cx.notify(); // Trigger re-render
});
// Weak reference (for closures/callbacks)
let weak = counter.downgrade();
let _ = weak.update(cx, |state, cx| {
state.count += 1;
cx.notify();
});rust
// Create entity
let counter = cx.new(|cx| Counter { count: 0 });
// Read state
let count = counter.read(cx).count;
// Update state
counter.update(cx, |state, cx| {
state.count += 1;
cx.notify(); // Trigger re-render
});
// Weak reference (for closures/callbacks)
let weak = counter.downgrade();
let _ = weak.update(cx, |state, cx| {
state.count += 1;
cx.notify();
});In Components
在组件中使用
rust
struct MyComponent {
shared_state: Entity<SharedData>,
}
impl MyComponent {
fn new(cx: &mut App) -> Entity<Self> {
let shared = cx.new(|_| SharedData::default());
cx.new(|cx| Self {
shared_state: shared,
})
}
fn update_shared(&mut self, cx: &mut Context<Self>) {
self.shared_state.update(cx, |state, cx| {
state.value = 42;
cx.notify();
});
}
}rust
struct MyComponent {
shared_state: Entity<SharedData>,
}
impl MyComponent {
fn new(cx: &mut App) -> Entity<Self> {
let shared = cx.new(|_| SharedData::default());
cx.new(|cx| Self {
shared_state: shared,
})
}
fn update_shared(&mut self, cx: &mut Context<Self>) {
self.shared_state.update(cx, |state, cx| {
state.value = 42;
cx.notify();
});
}
}Async Operations
异步操作
rust
impl MyComponent {
fn fetch_data(&mut self, cx: &mut Context<Self>) {
let weak_self = cx.entity().downgrade();
cx.spawn(async move |cx| {
let data = fetch_from_api().await;
// Update entity safely
let _ = weak_self.update(cx, |state, cx| {
state.data = Some(data);
cx.notify();
});
}).detach();
}
}rust
impl MyComponent {
fn fetch_data(&mut self, cx: &mut Context<Self>) {
let weak_self = cx.entity().downgrade();
cx.spawn(async move |cx| {
let data = fetch_from_api().await;
// Update entity safely
let _ = weak_self.update(cx, |state, cx| {
state.data = Some(data);
cx.notify();
});
}).detach();
}
}Core Principles
核心原则
Always Use Weak References in Closures
闭包中始终使用弱引用
rust
// ✅ Good: Weak reference prevents retain cycles
let weak = cx.entity().downgrade();
callback(move || {
let _ = weak.update(cx, |state, cx| cx.notify());
});
// ❌ Bad: Strong reference may cause memory leak
let strong = cx.entity();
callback(move || {
strong.update(cx, |state, cx| cx.notify());
});rust
// ✅ Good: Weak reference prevents retain cycles
let weak = cx.entity().downgrade();
callback(move || {
let _ = weak.update(cx, |state, cx| cx.notify());
});
// ❌ Bad: Strong reference may cause memory leak
let strong = cx.entity();
callback(move || {
strong.update(cx, |state, cx| cx.notify());
});Use Inner Context
使用内部上下文
rust
// ✅ Good: Use inner cx from closure
entity.update(cx, |state, inner_cx| {
inner_cx.notify(); // Correct
});
// ❌ Bad: Use outer cx (multiple borrow error)
entity.update(cx, |state, inner_cx| {
cx.notify(); // Wrong!
});rust
// ✅ Good: Use inner cx from closure
entity.update(cx, |state, inner_cx| {
inner_cx.notify(); // Correct
});
// ❌ Bad: Use outer cx (multiple borrow error)
entity.update(cx, |state, inner_cx| {
cx.notify(); // Wrong!
});Avoid Nested Updates
避免嵌套更新
rust
// ✅ Good: Sequential updates
entity1.update(cx, |state, cx| { /* ... */ });
entity2.update(cx, |state, cx| { /* ... */ });
// ❌ Bad: Nested updates (may panic)
entity1.update(cx, |_, cx| {
entity2.update(cx, |_, cx| { /* ... */ });
});rust
// ✅ Good: Sequential updates
entity1.update(cx, |state, cx| { /* ... */ });
entity2.update(cx, |state, cx| { /* ... */ });
// ❌ Bad: Nested updates (may panic)
entity1.update(cx, |_, cx| {
entity2.update(cx, |_, cx| { /* ... */ });
});Common Use Cases
常见使用场景
- Component State: Internal state that needs reactivity
- Shared State: State shared between multiple components
- Parent-Child: Coordinating between related components (use weak refs)
- Async State: Managing state that changes from async operations
- Observations: Reacting to changes in other entities
- 组件状态:需要响应式的内部状态
- 共享状态:多组件间共享的状态
- 父子组件:协调关联组件间的交互(使用弱引用)
- 异步状态:管理由异步操作变更的状态
- 状态监听:响应其他实体的状态变更
Reference Documentation
参考文档
Complete API Documentation
完整API文档
- Entity API: See api-reference.md
- Entity types, methods, lifecycle
- Context methods, async operations
- Error handling, type conversions
- Entity API:查看 api-reference.md
- 实体类型、方法、生命周期
- 上下文方法、异步操作
- 错误处理、类型转换
Implementation Guides
实现指南
-
Patterns: See patterns.md
- Model-view separation, state management
- Cross-entity communication, async operations
- Observer pattern, event subscription
- Pattern selection guide
-
Best Practices: See best-practices.md
- Avoiding common pitfalls, memory leaks
- Performance optimization, batching updates
- Lifecycle management, cleanup
- Async best practices, testing
-
Advanced Patterns: See advanced.md
- Entity collections, registry pattern
- Debounced/throttled updates, state machines
- Entity snapshots, transactions, pools
-
设计模式:查看 patterns.md
- 模型-视图分离、状态管理
- 跨实体通信、异步操作
- 观察者模式、事件订阅
- 模式选择指南
-
最佳实践:查看 best-practices.md
- 避免常见陷阱、内存泄漏
- 性能优化、批量更新
- 生命周期管理、资源清理
- 异步最佳实践、测试
-
高级模式:查看 advanced.md
- 实体集合、注册器模式
- 防抖/节流更新、状态机
- 实体快照、事务、对象池