Problem:
I am subscribing to a ChildAdded event and unsubscribing to said event upon clicking 1 of 2 buttons. E.g., if I click the "DisableGlobalChat" button, then I'd expect the current listener to be removed. If I click the "EnableGlobalChat" button, then I'd expect a new listener to be added. The problem is that when disabling and then re-enabling, duplicate listeners are being added, or else the previous listener is not being deactivated.
Goal:
Prevent duplicate listeners being added when disabling and then re-enabling the listener.
Question:
My code is shown below with comments throughout. Is there an issue in this code that would cause duplicate listeners?
Code/Background:
Relevant guide: https://firebase.google.com/docs/database/unity/retrieve-data. Similar post: How do you unsubscribe Firebase ChildAdded events in Unity C#?.
public void CurrentListener2(object o2, ChildChangedEventArgs args2) //o2 does not do anything, this is how we instantiate the messages after listening
{
if (args2.DatabaseError != null)
{
Debug.Log("there were errors");
}
else //upon disabling and enabling the listener, 2 listeners are added. Do it again and the number goes up to 3, etc. This is causing messages to be instantiated multiple times.
{
globalJson = JsonUtility.FromJson<GlobalDeserialiseJson>(args2.Snapshot.GetRawJsonValue());
InstantiateMessageGlobal(globalJson.globalSenderUsername.ToString(), globalJson.globalSenderID.ToString(), globalJson.globalMessageText.ToString());
}
}
public void GlobalListenForNewMessages() //if global chat is not disabled then add a listener for new childs in the global chat node
{
if (PlayerPrefs.GetString("DisableGlobal") == "F" || PlayerPrefs.HasKey("DisableGlobal") == false)
{
//globalListener = CurrentListener2; //trying to set CurrentListener2 to a variable to see if that would change anything, it did not
globalReference.LimitToLast(1).ChildAdded += CurrentListener2; //looking to the global node, limiting to the most recent message, and adding a listener
Debug.Log("enabled"); //tracking changes
}
}
public void GlobalStopListenForNewMessages()///if global chat is disabled then remove the current listener
{
if (PlayerPrefs.GetString("DisableGlobal") == "T")
{
globalReference.LimitToLast(1).ChildAdded -= CurrentListener2; //looking to the global node, limiting to the most recent message, and removing a listener
//globalListener = null; //setting the globalListener to null to see if that would change anything, it did not
Debug.Log("disabled"); //tracking changes
}
}
public void DisableGlobalChat() //clicking button to disable global chat
{
PlayerPrefs.SetString("DisableGlobal", "T");
PlayerPrefs.Save();
GlobalStopListenForNewMessages(); //stop listening for messages
}
public void EnableGlobalChat() //clicking button to enable global chat
{
PlayerPrefs.SetString("DisableGlobal", "F");
PlayerPrefs.Save();
GlobalListenForNewMessages(); //start listening for messages
}