0

I got this firebase observer in my playersRef child node as:

playersRef = FirebaseDatabase.DefaultInstance.GetReference("players");
playersRef.OrderByChild("level") .ValueChanged += (object sender2, ValueChangedEventArgs e2) => {}

Now, when my game object is destroyed. I want to remove this observer at playerRef which is called on some value changes.

PROBLEM: I cannot find any way to silence this observer. Like in other languages , firebase allows us to removeAllObservers() like as :

 ref.removeAllObservers()

But , in unity C# searching through firebase doc, I see no option to remove observers. https://firebase.google.com/docs/reference/unity/class/firebase/database/database-reference

Any help would be highly appreciated. Thanks in advance.

user3804063
  • 809
  • 1
  • 14
  • 32

2 Answers2

0

Answer lies in this link, you can unsubscribe from the event by using (-) operator.

Hamid Yusifli
  • 9,688
  • 2
  • 24
  • 48
user3804063
  • 809
  • 1
  • 14
  • 32
0

Just to expand on the previous answer. You'll want to do the following:

1) Actually name the function to handle the event (so you can -= it later):

private void HandleValueChanged(object sender, ValueChangedEventArgs args) {
}

2) Cache the reference to the Query that you'll be using ValueChanged with:

Query _cachedQuery;

void Start() {
    playersRef = FirebaseDatabase.DefaultInstance.GetReference("players");
    _cachedQuery = playersRef.OrderByChild("level");
    _cachedQuery.ValueChanged += HandleValueChanged;
}

3) When you're done, remove the listener. For bonus points, check if it's non null (ie: if you do use Start instead of Awake, this will handle the case that the object had DestroyImmediate called on it before the first update loop).

void OnDestroy() {
    if (_cachedQuery != null) {
        _cachedQuery -= HandleValueChanged;
        _cachedQuery = null;
    }
}

C# itself generally does not allow you to "RemoveAll" from an event (you can work around this though). But if you're used to that pattern or (like me) prefer to work in UnityEvents, you can always do all of this in a class that exposes a UnityEvent. Then you can call RemoveAllListeners on this proxy class you create (although I would consider RemoveAll a "code smell" in my own personal style, it's up to each team to decide what they do and don't consider good code).

Patrick Martin
  • 2,993
  • 1
  • 13
  • 11