Firebase Offline Capabilities and addListenerForSingleValueEvent

后端 未结 4 756
无人及你
无人及你 2020-11-21 22:21

Whenever I use addListenerForSingleValueEvent with setPersistenceEnabled(true), I only manage to get a local offline copy of DataSnapshot

4条回答
  •  长情又很酷
    2020-11-21 23:24

    When workinkg with persistence enabled, I counted the times the listener received a call to onDataChange() and stoped to listen at 2 times. Worked for me, maybe helps:

    private int timesRead;
    private ValueEventListener listener;
    private DatabaseReference ref;
    
    private void readFB() {
        timesRead = 0;
        if (ref == null) {
            ref = mFBDatabase.child("URL");
        }
    
        if (listener == null) {
            listener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //process dataSnapshot
    
                    timesRead++;
                    if (timesRead == 2) {
                        ref.removeEventListener(listener);
                    }
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            };
        }
        ref.removeEventListener(listener);
        ref.addValueEventListener(listener);
    }
    

提交回复
热议问题