66 lines
2.0 KiB
C#
66 lines
2.0 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
namespace BaseGames.Core.Events
|
||
{
|
||
/// <summary>
|
||
/// 单条订阅的 Disposable 句柄。Dispose() 自动取消注册。
|
||
/// </summary>
|
||
public readonly struct EventSubscription : IDisposable
|
||
{
|
||
private readonly Action _unsubscribe;
|
||
|
||
public EventSubscription(Action unsubscribe)
|
||
=> _unsubscribe = unsubscribe;
|
||
|
||
public void Dispose() => _unsubscribe?.Invoke();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 批量管理多条订阅,统一在 Dispose / Clear 时取消所有注册。
|
||
/// 用法:OnEnable 调用 Subscribe,OnDisable 调用 Clear。
|
||
/// </summary>
|
||
public sealed class CompositeDisposable : IDisposable
|
||
{
|
||
private readonly List<IDisposable> _items = new();
|
||
|
||
public void Add(IDisposable item) => _items.Add(item);
|
||
|
||
public void Clear()
|
||
{
|
||
foreach (var item in _items) item.Dispose();
|
||
_items.Clear();
|
||
}
|
||
|
||
public void Dispose() => Clear();
|
||
}
|
||
|
||
/// <summary>
|
||
/// <see cref="EventSubscription"/> 扩展方法(架构 02 §8)。
|
||
/// </summary>
|
||
public static class EventSubscriptionExtensions
|
||
{
|
||
/// <summary>
|
||
/// 将订阅句柄添加到集合中,统一生命周期管理。
|
||
/// 用法:channel.Subscribe(Handler).AddTo(_subscriptions);
|
||
/// </summary>
|
||
public static EventSubscription AddTo(this EventSubscription subscription,
|
||
ICollection<IDisposable> collection)
|
||
{
|
||
collection.Add(subscription);
|
||
return subscription;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 将订阅句柄添加到 <see cref="CompositeDisposable"/> 中。
|
||
/// </summary>
|
||
public static EventSubscription AddTo(this EventSubscription subscription,
|
||
CompositeDisposable compositeDisposable)
|
||
{
|
||
compositeDisposable.Add(subscription);
|
||
return subscription;
|
||
}
|
||
}
|
||
}
|