Gathering data from Firebase asynchronously: when is the data-set complete?

断了今生、忘了曾经 提交于 2020-01-06 14:47:52

问题


in a Firebase Android app that I'm currently developing I would like to provide an export feature. This feature should allow the user to export a set of data that is stored in Firebase.

My plan is to gather all required data into a intermediate object (datastructure) that can be (re-)used for multiple export types.

I am running into the issue that because of the flat Firebase data structure that I am using (as explained in https://www.firebase.com/docs/android/guide/structuring-data.html), it's difficult to know when all the data required for the export has been collected.

Example: when retrieving all objects that are referenced using 'indices' (name: key, value true), for each of these I set an addListenerForSingleValueEvent listener, but because this returns asynchronous, it's impossible to determine when all the indices are retrieved. This way it's not possible to determine the correct moment to start the export.

Who has best practices for coping with this?


回答1:


Posting this to show a worked out example of the comment of @FrankvanPuffelen that seems to do the job quite well:

@Override
public void onDataChange(DataSnapshot indexListDataSnapshot) {
    final long participantsRequired = indexListDataSnapshot.getChildrenCount();

    for (DataSnapshot ds : indexListDataSnapshot.getChildren()) {
        DataUtil.getParticipantByKey( mEventKey, ds.getKey() ).addListenerForSingleValueEvent( new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Participant p = dataSnapshot.getValue(Participant.class);
                mParticipants.add( p );

                if (participantsRequired == mParticipants.size()){
                    executeExport();
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                mListener.onDataLoadFailure( firebaseError.toException() );
            }
        });
    }
}


来源:https://stackoverflow.com/questions/36108608/gathering-data-from-firebase-asynchronously-when-is-the-data-set-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!