firestore read is asynchronous and I want synchronous behaviour

前端 未结 2 1578
隐瞒了意图╮
隐瞒了意图╮ 2021-01-16 23:47

I want to store locally the data I am reading from the cloud. To achieve this I am using a global variable(quizzes) to hold all the data.

For this, whe

2条回答
  •  别那么骄傲
    2021-01-17 00:13

    You can make your own callback. For this, make an interface

    public interface FireStoreResults {
        public void onResultGet();
    }
    

    now send this call back when you get results

    public void readData(final FireStoreResults){
        db.collection("users").document(user_id).collection("quizzes")
        .get().addOnSuccessListener(new OnSuccessListener() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                         Quiz quizDownloaded = getQuizFromCloud(document.getId());
                         quizzes.add(quizDownloaded);
                     }
                    results.onResultGet();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    results.onResultGet();
                }
            });   
    }
    

    Now in your activity or fragment

    new YourResultGetClass().readData(new FireStoreResults(){
                 @Override
                 public void onResultGet() {
                        new YourResultGetClass().getQuizzes(); //this is your list of quizzes
                        //do whatever you want with it
                }
    

    Hope this makes sense!

提交回复
热议问题