Should I actually remove the ValueEventListener?

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


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 14:18

    To remove the ValueEventListener, you can then do this:

    Remove the anonymity of the listener.

    Change the code from this:-

          Ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
    
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    

    into this:

       ValueEventListener listener= new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
    
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    Ref.addValueEventListener(listener);
    

    Now you will be able to remove the listener:

       @Override
    public void onDestroy() {
    if (Ref != null && listener != null) {
       Ref.removeEventListener(listener);
        }
     }
    

    You need to remove it, so the listener does not stay running in the other activity lifecycles like onDestroy()

提交回复
热议问题