Firestore offline write events - java

Firestore call onComplete etc events only online. How do know about write status offline.
db.collection("col").document(id).set(obj)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//Ok finish activity <----
finish();
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Error try again", Toast.LENGTH_SHORT);
toast.show();
}
}
});
The code above doesn't works offline, and i can write multiple times. onComplete will not called until i connect to internet. Ho do i implement this feature(closing activity when success).

onComplete will not be called until I connect to the internet.
That's normal behavior. The OnCompleteListener is called only when the data has been written or rejected by the Firebase servers.
A listener will never fire for local write operations. If the local write operation were to fail, the client will raise a regular exception. The Firestore client is designed to continue working even if offline. So writing some data to the database while offline will never produce an error.
Ho do I implement this feature(closing activity when success).
There is no way you can add a completion listener to know when the data is written to the cache and this is because this operation is happening instantly. There is nothing you should worry about in this situation.
What you can in such cases is to check the internet connection. If you are offline, it means that all data is added to the local cache.

Offline writes are considered to be written immediately. There is no completion status for that.
You'll notice that if you have a listener set up for the document that's being written, that listener will trigger immediately, while offline, with the updated document values. You can tell from the document snapshot delivered to the listener if the write has completed or not. If you call snapshot.getMetadata().hasPendingWrites(), it will tell you whether or not the updated document has actually been sent. This is the best possible information you can receive about the status of offline writes.

Related

Android Cloud Firestore task's return successfully when there is no internet connection. How?

I'm messing around with Cloud Firestore.
I would like to simply get a callback when reading from DB fails, so I can show a dialog to the user about he has no internet connection. Of course, this would need sophisticated exception handling, but first things first, I would like to just simply get a callback when the app cannot reach the server.
HOWEVER, whenever I test my application with an emulator which has no internet connection, I still get successful callbacks.
This is the log:
Logging_: onSuccess
Logging_: onComplete
Logging_: Task was successful without an internet connection, how?
How is it possible? Am I thinking right that Cloud Firestore is simply not available for this use case since it was built to provide cached data and aggressive syncing in order to provide a seamless user experience even when there is no internet connection?
I would just need a way to just KNOW whether the DB is reachable. (a.k.a - Is there an internet connection problem?)
Code is really simple, it just tries to reach for the current account's characters.
db.collection("users")
.document(accountId)
.collection("characters")
.get()
.addOnCanceledListener(new OnCanceledListener() {
#Override
public void onCanceled() {
Log.i("Logging_", "onCanceled");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Logging_", "onFailure");
}
})
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
Log.i("Logging_", "onSuccess");
}
})
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
Log.i("Logging_", "onComplete");
if (task.isSuccessful()) {
Log.i("Logging_", "Task was successful without internet connection, how?");
} else {
Log.i("Logging_", "Task wasn't successful.");
}
}
});
I would like to simply get a callback when reading from DB fails, so I can show a dialog to the user about whether he has no internet connection.
The Firestore SDK doesn't throw an error when there is no internet connection, and it makes sense since Firestore is designed to work offline. Behind the scenes, Firestore SDK tries to reconnect until the devices regain connectivity. So not having an internet connection cannot be considered a failure. If you want to check for internet connectivity, the following answer might help:
How to verify if user has network access and show a pop-up alert when there isn't
Please notice that Firestore has a built-in mechanism that can help know when an error occurs. So the failure callback occurs when Firestore servers reject the request due to a security rule issue.
There is a solution in which you can force the retrieval of data only from the cache or from the server. Here is the official documentation regarding source options:
https://firebase.google.com/docs/firestore/query-data/get-data#source_options
Firestore has built in caching that is enabled by default for reading from a database on Apple and Android devices. If you want to disable being able to read the cached data, you can do something like this:
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(false)
.build();
db.setFirestoreSettings(settings);
I think what you may want to do instead is listen to network events in Android which would allow you to update the user if they try to perform an action while there is no network available.
This might be a bug. I have logged the tracking info here on GitHub

How to make sure Firebase fetches data from the server only

I want to be able to fetch data from Firebase server only and if there is no internet connection it should show a failure message.
Source source = Source.SERVER;
firebaseFirestore.collection("stock").document(pid).get(source).addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String prod_id = document.getString("pid");
}
}
});
I tried doing the above but it still loads cached results if there is no internet.
Please help.
I want to be able to fetch data from firebase server only
This is exactly what your code does. By specifying Source.SERVER, you are telling Firestore to return only data from the server.
if there is no internet connection it should show a failure message.
onFailure() fires only when there is a problem in reading documents, for example, when you don't have permission to access them. In other words, when Firebase server rejects the read operation due to the permissions that are set the in security rules. onFailure() will never fire when there is no internet connection on user device and it makes sense since you need to access the data while offline. This cannot be considered a failure.
I tried doing the above but it still loads cached results if there is no internet.
That's normal behavior. The Firestore SDK caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline.
Edit:
According to #FrankvanPuffelen comment, in the official documentation is also mentioned that:
public static final Source SERVER
Causes Cloud Firestore to avoid the cache, generating an error if the server cannot be reached. Note that the cache will still be updated if the server request succeeds. Also note that latency-compensation still takes effect, so any pending write operations will be visible in the returned data (merged into the server-provided data).

Firestore admin "listens" to all documents again on reboot

TL;DR
Every time my Fiestore admin server reboots my document listener is triggered for all documents even if I have already listened to the document and processed it. How do I get around this?
End TL;DR
I'm working on building a backend for my Firestore chat application. The basic idea is that whenever a users enters a chat message through a client app the backend server listens for new messages and processes them.
The problem I'm running into is that whenever I reboot my app server the listener is triggered for all of the existing already processed chats. So, it will respond to each chat even though it has already responded previously. I would like the app server to only respond to new chats that it hasn't already responded to.
One idea I have for a work around is to put a boolean flag on each chat document. When the backend processes the chat document it will set the flag. The listener will then only reply to chats that don't have the flag set.
Is this a sound approach or is there a better method? One concern I have is that every time I reboot my app server I will be charged heavily to re-query all of the previous chats. Another concern I have is that listening seems memory bound? If my app scales massively will I have to store all chat documents in memory? That doesn't seem like it will scale well...
//Example listener that processes chats based on whether or not the "hasBeenRepliedTo" flag is set
public void startFirestoreListener() {
CollectionReference docRef = db.collection("chats");
docRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, #javax.annotation.Nullable FirestoreException e) {
if(e != null) {
logger.error("There was an error listening to changes in the firestore chats collection. E: "+e.getLocalizedMessage());
e.printStackTrace();
}
else if(queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
for(ChatDocument chatDoc : queryDocumentSnapshots.toObjects(ChatDocument.class)) {
if(!chatDoc.getHasBeenRepliedTo() {
//Do some processing
chatDoc.setHasBeenRepliedTo(true); //Set replied to flag
}
else {
//No-op, we've already replied to this chat
}
}
}
}
});
}
Yes, to avoid getting each document all the time, you will have to construct a query that yields only the documents that you know have been processed.
No, you are not charged to query documents. You are charged only to read them, which will happen if your query yields documents.
Yes, you will have to be able to hold all the results of a query in memory.
Your problem will be much easier to solve if you use Cloud Functions to receive events for each new document in a collection. You won't have to worry about any of the above things, and instead just worry about writing a Firestore trigger that does what you want with each new document, and paying for those invocations.

About Firestore is there some flag I can check if the data is on/off line data?

I read when on Android in offline mode the onComplete() method will never return unless the device goes online so data can be persisted to the backen at Firestore.
When I'm in offline mode and do this get() I notice that it return with what I think must be local data since I have the setPersistenceEnabled(true)
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
}
});
I just have to ask if this is correct? If so is there some flag I can check if the data is online/offline data?
Sometimes doing this get() it does not return just hangs there forever, maybe that has to do with my device getting warm after heavy debugging.
Unlike in Firebase Realtime database where to enable offline persistence you should have used first, the following line of code:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
In Cloud Firestore, for Android and iOS, offline persistence is enabled by default. So, there is no need to use: setPersistenceEnabled(true).
When you are offline and you are using a get() call, the result will be from the cached copy of the Cloud Firestore data that your app is actively using.
To check if the data is from cache or from Firestore servers, you can use the following line of code:
String source = querySnapshot.getMetadata().isFromCache() ? "Local Cache" : "Firebase Server";

Fire base not call onCancelled if timeout or not able to access server

I a using firebase and found and issue that firebase not send error for timeout or if not able to connect to server. In that case we are unable to provide correct information to user what the issue is.
Firebase developers must handle this very common use-case. Did anyone encounter this issue?
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot data) {
}
#Override
public void onCancelled(FirebaseError arg0) {
}
Utilize .info/connected to monitor connection state. Firebase works while offline and your onCancelled event is not going to be fired because it is still waiting for the connection to be restored so the message can be delivered.
Firebase is a real-time sync platform. You cannot keep data in sync without any internet access (how will local and remote be reconciled?). So you need to utilize disk persistence (in beta on iOS) or at least have an initial connection to get things moving. Check out offline capabilities for details on all of these topics.

Categories