Files
Workspace/Assets/Modules/ShrinkContext.EventBusAdapter/Runtime/ShrinkEventBusEffects.cs
T

57 lines
2.0 KiB
C#

#nullable enable
using System;
using Cysharp.Threading.Tasks;
using ShrinkContext;
using ShrinkEventBus;
namespace ShrinkContext.EventBusAdapter
{
/// <summary>
/// 把 ShrinkEventBus 的订阅/注册包装为可逆效应:
/// <c>IShrinkEventSubscription.Dispose</c> 天然就是订阅的逆操作——
/// 组件在 apply 里订阅,停用时随上下文自动退订,无需手写卸载路径。
/// </summary>
public static class ShrinkEventBusEffects
{
/// <summary>订阅事件即效应:ctx 卸载或手动 Dispose 句柄时自动退订。</summary>
public static ShrinkEffectHandle EffectSubscribe<TEvent>(
this ShrinkCtx ctx,
Action<TEvent> handler,
EventPriority priority = EventPriority.NORMAL,
bool receiveCanceled = false)
where TEvent : EventBase
{
if (ctx == null)
throw new ArgumentNullException(nameof(ctx));
if (handler == null)
throw new ArgumentNullException(nameof(handler));
var subscription = EventBus.SubscribeEvent(handler, priority, receiveCanceled);
return ctx.EffectInverse(() =>
{
subscription.Dispose();
return UniTask.CompletedTask;
});
}
/// <summary>
/// 实例对象整体注册即效应:扫描对象上的 [EventSubscribe] 方法(含未织入的非 MonoBehaviour 类),
/// 逆操作为 Unregister。
/// </summary>
public static ShrinkEffectHandle EffectRegister(this ShrinkCtx ctx, object target)
{
if (ctx == null)
throw new ArgumentNullException(nameof(ctx));
if (target == null)
throw new ArgumentNullException(nameof(target));
EventBus.Register(target);
return ctx.EffectInverse(() =>
{
EventBus.Unregister(target);
return UniTask.CompletedTask;
});
}
}
}