Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preventing Pending Writes in Firebase with Transactions Not Working

I aim to insert the name in Firestore when the button is clicked, but I don’t want the save to be pending if the user is not connected to the internet. I don’t like the behavior of Firebase where it saves pending writes, even if the internet connection is restored.

I researched and found that Firebase developers suggest using transactions to prevent pending writes when there is no internet. I have tried this, but the result is still the same: if there is no internet, it saves pending writes, and when the internet connection is restored, it rewrites to Firestore. Why aren’t transactions working as expected?

HashMap < String, Object > hashMap = new HashMap < > ();
hashMap.put("Name", "Test");

FirebaseFirestore.getInstance().batch().set(FirebaseFirestore.getInstance().collection("LISTS").document(), hashMap).commit().addOnCompleteListener(new OnCompleteListener < Void > () {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        Toast.makeText(MainActivity.this, "" + task, Toast.LENGTH_SHORT).show();
        if (task.isSuccessful())
            activityMainBinding.activityMainMaterialToolbarTopBar.setTitle("Done");
        else
            activityMainBinding.activityMainMaterialToolbarTopBar.setTitle(task.getException().getMessage());
    }
});

I am short on time as I want to deliver this project to the company on the specified date, and I don’t want to waste time. If it’s not possible to solve the problem with transactions, please let me know so I can look for alternative solutions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you’re using FirebaseFirestore#batch() you aren’t performing a transaction, but creating a WriteBatch:

Creates a write batch, used for performing multiple writes as a single atomic operation.

So, it’s an atomic operation and not a transaction. If you need to perform a transaction, please check the official documentation below:

So you should use FirebaseFirestore#runTransaction() which:

Executes the given updateFunction and then attempts to commit the changes applied within the transaction.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading