Home > database >  Preventing Pending Writes in Firebase with Transactions Not Working
Preventing Pending Writes in Firebase with Transactions Not Working

Time:02-01

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.

CodePudding user response:

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.

  • Related