java - 为什么在调用 WriteResult 之前,batch.commit() 不起作用?

标签 java android firebase google-cloud-firestore

我有一个 Firestore 数据库,我在其中写入数据 WriteBatch()。 因此,我在提交更改时遇到了奇怪的行为。 仅当我使用 batch.commit() 的变量执行某些操作时,我的数据才会更新或设置 代码应该更好地解释我的问题:

...
...
Firestore db = FirestoreClient.getFirestore();       

Map<String, Foo> test = new HashMap<>();
test.put("Entry1", new Foo("Bar1", 5));
test.put("Entry2", new Foo("Bar2", 7));

WriteBatch batch = db.batch();
DocumentReference ref;

for (String key : test.keySet()) {
    ref = db.collection("foo").document(key);
    batch.set(ref, test.get(key), SetOptions.mergeFields("var1", "var2"));
}

// if I just call batch.commit() here data will not be overwritten on a change of i.e "Entry1"

// but if I call the next 2 lines everything is working as intended
ApiFuture<List<WriteResult>> result = batch.commit();
result.get();

我在代码中添加这些行没有问题,但我试图理解为什么会发生这种情况。

最佳答案

根据您的评论:

The last 2 lines of code in my example. If they are missing, changes won't be written to firestore. As I understand it should be irrelevant if I save the return value of batch.commit() or not.

如果缺少这两行代码,更准确地说是缺少 commit() 的代码,则不会发生任何事情,因为您没有向批处理提交任何内容。是的,你是对的,无论是否将 batch.commit() 的结果保存到 result 对象中,commit () 方法将始终在该对象上被调用。因此,只有当您对批处理对象调用 commit() 时,才会将批处理写入 Firestore 中,否则之前存在的代码行将毫无用处。

关于java - 为什么在调用 WriteResult 之前,batch.commit() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039385/

相关文章:

java - 如何通过 Java 代码在没有完整 CN/DN 的情况下连接 Active Directory

java - 如何弄清楚为什么某些 javax.servlet 依赖项被添加到 Maven 项目中

java - 这里哪些同步语句是不必要的?

java - 静态变量可以在运行时分配内存吗

android - 扩展 View 并使用 onLongclick

android - Android Studio是否会自动尝试更新库?

javascript - Firebase 更新值的速度没有我想要的 Javascript 快

android - FindViewByID 为 CustomView 返回 null

swift - 从 Children Firebase 访问值

firebase - 如何在 Firestore 中处理自定义用户排序