C
C#14mo ago
WxAaRoNxW

❔ Am I doing event subscription correctly?

I have 2 singleton classes SingletonA, working mostly alone and has events and the other, SingletonB can also work alone but in my code, needs to rely on the A's events so that it functions. both are initialized at the same time, both are uninitialized at the same time on initialization, SingletonB subscribes to SingletonA and on uninitialization SingletonB unsubscribes to SingletonA
// SingletonB
public void EnableClass()
{
TrackingAssistant.Instance.OnTrackedObjectAdd += OnTrackedObjectAdd;
TrackingAssistant.Instance.OnTrackedObjectRemove += OnTrackedObjectRemove;
TrackingAssistant.Instance.OnTrackedObjectUpdate += OnTrackedObjectUpdate;
TrackingAssistant.Instance.OnTrackedObjectsReload += OnTrackedObjectsReload;
}

public void DisableClass()
{
TrackingAssistant.Instance.OnTrackedObjectAdd -= OnTrackedObjectAdd;
TrackingAssistant.Instance.OnTrackedObjectRemove -= OnTrackedObjectRemove;
TrackingAssistant.Instance.OnTrackedObjectUpdate -= OnTrackedObjectUpdate;
TrackingAssistant.Instance.OnTrackedObjectsReload -= OnTrackedObjectsReload;
}
// SingletonB
public void EnableClass()
{
TrackingAssistant.Instance.OnTrackedObjectAdd += OnTrackedObjectAdd;
TrackingAssistant.Instance.OnTrackedObjectRemove += OnTrackedObjectRemove;
TrackingAssistant.Instance.OnTrackedObjectUpdate += OnTrackedObjectUpdate;
TrackingAssistant.Instance.OnTrackedObjectsReload += OnTrackedObjectsReload;
}

public void DisableClass()
{
TrackingAssistant.Instance.OnTrackedObjectAdd -= OnTrackedObjectAdd;
TrackingAssistant.Instance.OnTrackedObjectRemove -= OnTrackedObjectRemove;
TrackingAssistant.Instance.OnTrackedObjectUpdate -= OnTrackedObjectUpdate;
TrackingAssistant.Instance.OnTrackedObjectsReload -= OnTrackedObjectsReload;
}
but there are times when SingletonA unitializes first so the Instance reference is set to null leaving SingletonB's uninitialization throwing an exception. do I just slap a null condition before unsubscribing or is there a better way?
3 Replies
WxAaRoNxW
WxAaRoNxWOP14mo ago
also there's another singleton class that gets initialized late but doesn't rely on any classes as well, but singletonB relies on it to make some of its function work as well, what's a graceful way to subscribe to the events of singletonC if it has initialized
Omnissiah
Omnissiah14mo ago
technically there are a bunch of things you can do, but the point is what makes sense i imagine there should be an "uninitializing" condition that these objects should be aware of
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server