gpui-entity

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Overview

概述

An
Entity<T>
is a handle to state of type
T
, providing safe access and updates.
Key Methods:
  • entity.read(cx)
    &T
    - Read-only access
  • entity.read_with(cx, |state, cx| ...)
    R
    - Read with closure
  • entity.update(cx, |state, cx| ...)
    R
    - Mutable update
  • entity.downgrade()
    WeakEntity<T>
    - Create weak reference
  • entity.entity_id()
    EntityId
    - Unique identifier
Entity Types:
  • Entity<T>
    : Strong reference (increases ref count)
  • WeakEntity<T>
    : Weak reference (doesn't prevent cleanup, returns
    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

常见使用场景

  1. Component State: Internal state that needs reactivity
  2. Shared State: State shared between multiple components
  3. Parent-Child: Coordinating between related components (use weak refs)
  4. Async State: Managing state that changes from async operations
  5. Observations: Reacting to changes in other entities
  1. 组件状态:需要响应式的内部状态
  2. 共享状态:多组件间共享的状态
  3. 父子组件:协调关联组件间的交互(使用弱引用)
  4. 异步状态:管理由异步操作变更的状态
  5. 状态监听:响应其他实体的状态变更

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
    • 实体集合、注册器模式
    • 防抖/节流更新、状态机
    • 实体快照、事务、对象池