firestore read is asynchronous and I want synchronous behaviour

前端 未结 2 1553
隐瞒了意图╮
隐瞒了意图╮ 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:36

    I didn't understand if you tried this solution, but I think this is the better and the easier: add an onCompleteListener to the Task object returned from the get() method, the if the task is succesfull, you can do all your stuff, like this:

    private void downloadQuizzesFromCloud(){
    
    
    String user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
    final FirebaseFirestore db = FirebaseFirestore.getInstance();
    CollectionReference quizzesRefrence = db.collection("users").document(user_id).collection("quizzes");
    
    quizzesRefrence.get().addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (task.isSuccesful()) {
                   for (QueryDocumentSnapshot document : task.getResult()) {
                        Quiz quizDownloaded = getQuizFromCloud(document.getId());
                        quizzes.add(quizDownloaded);
                   }
                 }
             });
    }
    }
    

    In this way, you'll do all you have to do (here the for loop) as soon as the data is downloaded

提交回复
热议问题