question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Chain Firestore setDocument operations in offline

See original GitHub issue

Hello, great library! But here is a problem 😃

I need to chain Firebase-s setDocument operation in offline, but I can’t because library’s binding trying to wait till Task’s OnSuccessListener will be called.

How can I manage this?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
lcszccommented, Jun 23, 2018

Try4W is right. This library methods will use the firebase callback to emit data to Obversable when creating/adding documents to an collection.

The code below (from this library) will add a document to our database, but the single will never emit onSuccess either onError because these firebase’s callback: .addOnCompleteListener and .addOnFailure will only be called when we sync a POJO with the server. That is the problem. The document has been already added to our database but our single will never emit if the user has no network connection.

@Try4W, what I recommend for you is to clone this library and create some methods that focus primary on offline addition of documents. Getters methods of this library will work properly even if the user isn’t connected, so what we only need to do is to create new methods and avoid those callbacks.

@NonNull
public static Single<DocumentReference> addDocument(@NonNull final CollectionReference ref,
                                                    @NonNull final Object pojo) {
    return Single.create(new SingleOnSubscribe<DocumentReference>() {
        @Override
        public void subscribe(final SingleEmitter<DocumentReference> emitter) throws Exception {
            ref.add(pojo).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
                @Override
                public void onComplete(@NonNull Task<DocumentReference> task) {
                    emitter.onSuccess(task.getResult());
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if (!emitter.isDisposed())
                        emitter.onError(e);
                }
            });
        }
    });
`
1reaction
FrangSierracommented, Jun 28, 2018

Totally agree with @itscorey , I think that I will add a few methods regarding this issues to avoid errors when working during offline data. I’m thinking in this kind of approach:

The only way to retrieve a snapshot without internet connection is using the addSnapshotListener, so I’m using it to control errors. Also I would add a try/catch in the set method to control more error cases.

@NonNull
    public static Single<DocumentSnapshot> addDocumentOffline(@NonNull final DocumentReference ref,
                                                              @NonNull final Map<String, Object> data) {
        return Single.create(new SingleOnSubscribe<DocumentSnapshot>() {
            @Override
            public void subscribe(final SingleEmitter<DocumentSnapshot> emitter) {
                    final ListenerRegistration listener = ref.addSnapshotListener(new EventListener<DocumentSnapshot>() {
                        @Override
                        public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                            if (e != null) {
                                emitter.onError(e);
                            } else {
                                if (documentSnapshot != null) {
                                    documentSnapshot.getReference().set(data);
                                } else {
                                    emitter.onError(new NullPointerException("Empty Snapshot"));
                                }
                                emitter.onSuccess(documentSnapshot);
                            }
                        }
                    });

                    emitter.setCancellable(new Cancellable() {
                        @Override
                        public void cancel() {
                            listener.remove();
                        }
                    });
                }
        });

There should be a method for Add, another for Delete and another one for Update. However, I don’t know right now how to achieve this approach using Collections.addSnapshotListener because it returns a list of Documents. What do you think about this approach guys? Any better idea?

Thank you for the feedback!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Perform simple and compound queries in Cloud Firestore
Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection or collection group.
Read more >
Adding data | Firestore - Google Cloud
There are several ways to write data to Firestore: Set the data of a document within a collection, explicitly specifying a document identifier....
Read more >
Firestore pricing clarifications for offline cached data
As this queue grows, local operations and app startup will slow down. Nothing major, but over time these may add up. If Google...
Read more >
The JavaScript + Firestore Tutorial for 2020: Learn by Example
Cloud Firestore is a blazing-fast, serverless NoSQL database, perfect for ... a PDF version of this tutorial so you can read it offline....
Read more >
Advanced offline caching techniques in Cloud Firestore
Firestore SDKs implement a caching system that helps to reduce latency, support offline querying and mutations, and reduce billed document ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found