How to remove listener from Firebase Realtime Database

后端 未结 3 1315
清酒与你
清酒与你 2020-12-06 12:56

For receiving data from Firebase Realtime Database I need to register listener:

objectReference.addValueEventListener(valueEventListener);

相关标签:
3条回答
  • 2020-12-06 13:44

    You can also do it like this:

      componentWillUnmount() {
        firebase.database().ref('example').child(this.state.somethingDyamic).off('value');
      };
    
      doSomething() {
        firebase.database().ref('example').child(this.state.somethingDyamic).on('value', (snapshot) => {
          ...
       });
      }
    
    0 讨论(0)
  • 2020-12-06 13:51

    The correct way to remove a listener is to remove it accordingly to the life-cycle of your activity using this line of code:

    databaseReference.removeEventListener(valueEventListener);
    

    Note that, if you have added the listener in onStart you have to remove it in onStop. If you have added the listener in onResume you have to remove it in onPause. If you have added the listener in onCreate you have to remove it in onDestroy.

    But remember onDestroy is not always called.

    0 讨论(0)
  • 2020-12-06 13:54

    Its better to check whether listener is null or has an object, because if the listener object is null there will be a runtime error

    if(valueEventListener!=null){
      databaseReference.removeEventListener(valueEventListener);
    }
    
    0 讨论(0)
提交回复
热议问题