Java Firebase Admin SDK – DatabaseReference – setValue vs setValueAsync

huangapple go评论70阅读模式
英文:

Java Firebase Admin SDK - DatabaseReference - setValue vs setValueAsync

问题

使用Java - Firebase Admin SDK。

我需要对Firebase实时数据库进行两次更新。更新#1 必须在 更新#2 之前发生。

我之前使用的代码是:

ref.setValueAsync("update#1");
ref.setValueAsync("update#2");

但在非常罕见的情况下,更新#2更新#1 之前发生 - 这破坏了我们的用例;我将代码重构为:

ref.setValue("update#1", null);
ref.setValueAsync("update#2");

这个更改是基于这样的假设进行的,即setValue是一个同步调用,只有在 更新#1 完成后才会执行 更新#2。但我们已经注意到 更新#2更新#1 之前发生的情况仍然存在 - 尽管非常罕见。

英文:

Using Java - Firebase Admin SDK.

I have to make two updates on the Firebase Realtime Database. Update#1 has to happen and only then Update#2 should happen.

I was earlier using this :

ref.setValueAsync("update#1");
ref.setValueAsync("update#2");

But in very rare cases - update#2 was happening before update#1 - flow was breaking for our usecase; I refactored the code to this :

ref.setValue("update#1", null);
ref.setValueAsync("update#2");

This change was made with the assumption that setValue is a sync call and we will only go for update#2 once update#1 is done. But we have noticed that cases of update#2 happening before update#1 are still there - although very rare.

答案1

得分: 1

在非常罕见的情况下 - 在更新#1之前发生了更新#2

这是预期行为,因为这些操作是并行执行的。因此,第二个操作可能比第一个操作更快地完成。因此,连续调用两个操作并不能保证操作完成的顺序。

如果您需要在确保第一个操作完成后才执行第二个操作,那么您必须将实际数据和完成监听器传递给 setValue() 方法:

ref.setValue("data", new DatabaseReference.CompletionListener() {
  @Override
  public void onComplete(DatabaseError error, DatabaseReference dataRef) {
    if (error != null) {
      System.out.println("失败,原因是:" + error.getMessage());
    } else {
      //执行第二个操作。
    }
  }
})

因此,一旦第一个操作完成,在回调中执行第二个操作。

英文:

> But in very rare cases - update#2 was happening before update#1

That's the expected behavior since the operations run in parallel. So there can be cases in which the second operation completes faster than the first one. So simply calling an operation right after the other doesn't offer you any guarantee of the order in which the operations will complete.

If you need to perform the second operation, only when you're 100% sure that the first operation is complete, then you have to pass to setValue() method the actual data and a completion listener:

ref.setValue("data", new DatabaseReference.CompletionListener() {
  @Override
  public void onComplete(DatabaseError error, DatabaseReference dataRef) {
    if (error != null) {
      System.out.println("Failed because of " + error.getMessage());
    } else {
      //Perform the second operation.
    }
  }
})

So as soon as the first operation completes, inside the callback perform the second one.

huangapple
  • 本文由 发表于 2023年2月16日 15:46:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定