Should I actually remove the ValueEventListener?

后端 未结 3 1178
攒了一身酷
攒了一身酷 2020-11-22 13:51
        DatabaseReference Ref = FirebaseDatabase.getInstance().getReference(Constants.Client + \"/\" + path);
        Ref.keepSynced(true);
        Ref.addValueEvent         


        
3条回答
  •  再見小時候
    2020-11-22 14:06

    When talking about listeners, yes, you need to remove them accordingly to the life-cycle of your activity and for this you need to use the following line of code:

    databaseReference.removeEventListener(valueEventListener);
    

    Remember if you don't do this, you'll end up wasting your battery and bandwidth. So:

    1. If you have added the listener in onStart you have to remove it in onStop.
    2. If you have added the listener in onResume you have to remove it in onPause.
    3. If you have added the listener in onCreate you have to remove it in onDestroy.

    But remember onDestroy is not always called, so the last option in not always a good choice.

    There is another approach in which there is no need to remove the listener and that is when using addListenerForSingleValueEvent:

    Add a listener for a single change in the data at this location.

提交回复
热议问题