Skip to content

Instantly share code, notes, and snippets.

@mrkybe
Created April 12, 2025 00:57
Show Gist options
  • Save mrkybe/dc80e39a7a70bbb47abf773264b9a6c3 to your computer and use it in GitHub Desktop.
Save mrkybe/dc80e39a7a70bbb47abf773264b9a6c3 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System;
using UnityEngine;
public class SubscriptionTracker
{
public string Name => _owner.name;
private readonly MonoBehaviour _owner;
private readonly Dictionary<(object source, Delegate handler), Action> _subscriptions = new();
public SubscriptionTracker(MonoBehaviour owner)
{
_owner = owner;
}
public bool TrySubscribe(
object source,
Action<EventHandler> subscribeAction,
Action<EventHandler> unsubscribeAction,
EventHandler handler)
{
var key = (source, handler);
if (_subscriptions.ContainsKey(key))
return false;
subscribeAction(handler);
_subscriptions[key] = () => unsubscribeAction(handler);
return true;
}
public bool TrySubscribe<TEventArgs>(
object source,
Action<EventHandler<TEventArgs>> subscribeAction,
Action<EventHandler<TEventArgs>> unsubscribeAction,
EventHandler<TEventArgs> handler) where TEventArgs : EventArgs
{
var key = (source, handler);
if (_subscriptions.ContainsKey(key))
return false;
subscribeAction(handler);
_subscriptions[key] = () => unsubscribeAction(handler);
return true;
}
public bool Unsubscribe(object source, EventHandler handler)
{
var key = (source, handler);
bool result = false;
if (_subscriptions.ContainsKey(key))
{
result = true;
_subscriptions[key]();
}
_subscriptions.Remove(key);
return result;
}
public bool Unsubscribe<TEventArgs>(object source, EventHandler<TEventArgs> handler) where TEventArgs : EventArgs
{
var key = (source, handler);
bool result = false;
if (_subscriptions.ContainsKey(key))
{
result = true;
_subscriptions[key]();
}
_subscriptions.Remove(key);
return result;
}
public void UnsubscribeAll()
{
foreach (var unsubscribe in _subscriptions.Values)
{
unsubscribe();
}
_subscriptions.Clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment