#nullable enable using System; using Cysharp.Threading.Tasks; using ShrinkContext; using ShrinkEventBus; namespace ShrinkContext.EventBusAdapter { /// /// 把 ShrinkEventBus 的订阅/注册包装为可逆效应: /// IShrinkEventSubscription.Dispose 天然就是订阅的逆操作—— /// 组件在 apply 里订阅,停用时随上下文自动退订,无需手写卸载路径。 /// public static class ShrinkEventBusEffects { /// 订阅事件即效应:ctx 卸载或手动 Dispose 句柄时自动退订。 public static ShrinkEffectHandle EffectSubscribe( this ShrinkCtx ctx, Action 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; }); } /// /// 实例对象整体注册即效应:扫描对象上的 [EventSubscribe] 方法(含未织入的非 MonoBehaviour 类), /// 逆操作为 Unregister。 /// 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; }); } } }