Should I actually remove the ValueEventListener?

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


        
3条回答
  •  甜味超标
    2020-11-22 14:00

    I had the same issue and was causing a lot of memory leaks. So I created a new class that handles added listeners and removes them when the corresponding method (onPause(), onStop() or onDestroy()) is called. Uses the androidx.lifecycle library and is applicable to both activities and fragments (in fact, any class that implements LifecycleOwner).

    You can check the code here. You will probably be good to go without manually adding the androidx.lifecycle dependency, but you can also add this to your module-level build.gradle:

    implementation 'androidx.lifecycle:lifecycle-runtime:VERSION'
    

    In your current code, instead of:

    databaseReference.addValueEventListener(valueEventListener);
    // or
    databaseReference.addListenerForSingleValueEvent(valueEventListener);
    

    you need to use:

    addValueEventListener(databaseReference, valueEventListener); 
    // or
    addListenerForSingleValueEvent(databaseReference, valueEventListener);
    

    This is valid when called from activities or fragments that use FirebaseListenerHandler, as shown in the gist. If you need to add a Firebase listener in another situation (like services), you still have to manually remove them.

提交回复
热议问题