3

In the onCreate method of the MainActivity, I fetch data from the firebase (Colud):

fireDB.collection("users").document(connectedEmail).get()
    .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {

        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            if (documentSnapshot.exists()) {
                 List<DocumentReference> groups =  (List<DocumentReference>) documentSnapshot.get("groups");
                 if (groups != null && groups.size() > 0) {
                     connectedGroup = groups.get(0);
                 }
            }

            // more code
        }
}).addOnFailureListener(new OnFailureListener() {

    @Override
    public void onFailure(@NonNull Exception e) {
        Log.d(this.getClass().getName(), "addOnSuccessListener:failed");
    }
});

I fetch the group of the user and keep it in the connectedGroup field of MainActivity. The activity has a getter method:

public DocumentReference getConnectedGroupReference() {
        return this.connectedGroup;
}

In a fragment that I navigate to, from MainActivity, I call getConnectedGroupReference in order to get that field. But if I nevigate to the fragment fast enough, this field could be not set yet (because the call to the database is asynchronous. What's the best way to wait until the field is initialized? What should I do if addOnFailureListener was called and connectedGroup was not initialized? How to solve a race between the user navigating to the fragment and the database fetching that field?

The easiest solution is to fetch the group name again in the fragment, but is there a better way?

EDIT: I continued investigating and it looks like it's not smart to freeze the screen. Is there a better way?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • Check **[this](https://stackoverflow.com/questions/48499310/how-to-return-a-documentsnapshot-as-a-result-of-a-method/48500679#48500679)** out, vesii. – Alex Mamo Jun 11 '20 at 09:31
  • @AlexMamo Hi, I watched your video but I still don't get it. Is `readData` waiting for the data to be fetched? Or do I have to call `readData` every time I move into a new fragment, meaning I will have to iterate over the docs again? – vesii Jun 11 '20 at 15:56
  • Firebase API is asynchronous, so you should wait for the data until it becomes available. Alternatively, you can use LiveData and observe the same object from multiple places. – Alex Mamo Jun 11 '20 at 17:24

0 Answers0