简体   繁体   中英

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 inte.net. I don't like the behavior of Firebase where it saves pending writes, even if the inte.net connection is restored.

I researched and found that Firebase developers suggest using transactions to prevent pending writes when there is no inte.net. I have tried this, but the result is still the same: if there is no inte.net, it saves pending writes, and when the inte.net 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM