Files
XCSDD/docs/api/core/event/Subscribe.md

51 lines
1.1 KiB
Markdown
Raw Normal View History

# Event::Subscribe
```cpp
uint64_t Subscribe(Callback callback);
```
订阅事件回调。
**描述**
将回调函数添加到事件订阅列表中,并返回一个唯一的订阅 ID。该 ID 可用于后续退订。线程安全,可在任意线程调用。
**参数:**
- `callback` - 要订阅的回调函数,类型为 `std::function<void(Args...)>`
**返回:** `uint64_t` - 订阅 ID用于退订
**复杂度:** O(1) amortized
**示例:**
```cpp
#include <XCEngine/Core/Event.h>
using namespace XCEngine::Core;
// 定义事件
Event<int, float> damageEvent;
// 订阅多个回调
uint64_t id1 = damageEvent.Subscribe([](int damage, float time) {
printf("Damage taken: %d at time %f\n", damage, time);
});
uint64_t id2 = damageEvent.Subscribe([](int damage, float time) {
// 记录伤害日志
});
// 使用 lambda 表达式
auto callback = [](int damage, float time) {
// 处理伤害
};
uint64_t id3 = damageEvent.Subscribe(callback);
```
## 相关文档
- [Event 总览](event.md) - 返回类总览
- [Unsubscribe](Unsubscribe.md) - 退订事件
- [Invoke](Invoke.md) - 触发事件