[Unity] What is proper way to remove a ValueChanged Listener from a Reference?

1,257 views
Skip to first unread message

Patrick Ellul

unread,
Nov 29, 2016, 10:20:00 AM11/29/16
to Firebase Google Group
This is how the documentation recommends adding a listener.
 FirebaseDatabase.DefaultInstance
     
.GetReference("Leaders")
     
.ValueChanged += (object sender, ValueChangedEventArgs args) => {
       
if (args.DatabaseError != null) {
         
Debug.LogError(args.DatabaseError.Message);
         
return;
       
}
       
// Do something with the data in args.Snapshot
     
};

However there is no mention of how to properly remove a listener from a reference.
I tried the following, however the listener still kept triggering. 

var myRef = FirebaseDatabase.DefaultInstance
     
.GetReference("Leaders");
myRef.ValueChanged += MyMethod;
...
myRef.ValueChanged -= MyMethod;

Upon debugging, I could still see the listener attached.

Has anyone else had issues with this usecase?

Best regards.

Benjamin Wulfe

unread,
Nov 30, 2016, 2:38:38 PM11/30/16
to Firebase Google Group
Hey Patrick Firebase developer here.
In my testing on the latest SDK, unsubscribe is working for me.

FirebaseDatabase.DefaultInstance.RootReference.ValueChanged += MyHandler;

void MyHandler(object sender, ValueChangedEventArgs e) { 
 UnityEngine.Debug.Log("Changed!");
 FirebaseDatabase.DefaultInstance.RootReference.ValueChanged -= MyHandler;
}

results in a single message even after multiple edits in the console.  There was a bug on complex queries that was fixed in 1.01.
Also note that DatabaseReference objects are ephemeral in nature.  This means you can subscribe to an event on one instance of a DatabaseReference and unsubscribe from another.  As long as the path of the two match, the event should be unsubscribed.  But otherwise, you should be able to subscribe and unsubscribe to these events just like any other C# event (so what you show is correct and should be working).

The lambda form of subscribing (in the docs) is technically bad form since you cannot unsubscribe easily.  We'll see what we can do about updating the docs about unsubscribing.
Reply all
Reply to author
Forward
0 new messages