androidfirebasegoogle-cloud-firestoreparse-server

Getting a document synchronously using FireStore


I have been using parse-server as my backend and now migrating all my stuff to FireStore (specifically for storing additional user data). Now, with parse I could directly get the user data just by using ParseUser.getCurrentUser().getString(...). If I use FireStore, I have created a users collection and I can store a document for each user and it also supports local storage with offline support. But the problem I am facing is that I always need to use asynchronous/callback methods to get data from a document. Here is an example in android:

final DocumentReference docRef = mFirestore
                    .collection(USER_COLLECTION).document(mAuthApi.getCurrentUserId());
            docRef.get(Source.CACHE).addOnCompleteListener(task -> {
                if(task.isSuccessful()) {
                    ......
                } else {
                    ......
                }
            });

Is there a way where we can directly get data synchronously from DocumentReference assuming it is locally cached? Something like:

mFirestore.collection(USER_COLLECTION).document(mAuthApi.getCurrentUserId()).getString(...)

That would make things very easy for me as I need to replace ParseUser.getCurrentUser().getString(...) with an equivalent FireStore call in my entire code base.


Solution

  • Is there a way where we can directly get data synchronously from DocumentReference assuming it is locally cached?

    No, there is not in terms of responsive applications. You cannot force the retrieval of the data from the cache while you're connected to the server, as you cannot stop the retrieval of the data from the cache while you are not connected to the server.

    But not only Firebase Realtime Database or Cloud Firestore loads data asynchronously, almost all of modern other web APIs do, since it may take some time to get the data. So if you will force to get the data synchronously it will lead to unresponsive application dialogs for your users.

    The initial response for most developers is to try and "fix" this asynchronous behavior, which I personally recommend against this. The web is asynchronous, and as soon as you accept that, you'll learn how to become productive with modern web APIs.

    There is a very interesting post that was writen by Doug Stevenson, which will help you better understand this concept.