【问题标题】:Google Firebase Realtime Database setValue IF (condition)Google Firebase 实时数据库 setValue IF(条件)
【发布时间】:2018-01-26 14:00:50
【问题描述】:

Firebase 数据库:

{
  "balance" : 10
}

应用程序 1(伪代码):

if (balance-10 >= 0)
{
    // Application freezes for a few seconds. (Connection/hardware issue or whatever reason)
    balance -= 10;
}

应用程序 2(伪代码):

if (balance-10 >= 0)
{
    // Application is executed without any problems.
    balance -= 10;
}

如果两个应用程序同时启动,最终的“余额”值将是“-10”而不是“0”。

在 MySQL 中,这个问题很容易解决:

UPDATE `table` SET balance=IF(balance-10>=0, balance-10, balance);

Firebase 有哪些可能的解决方案?

【问题讨论】:

    标签: firebase firebase-realtime-database


    【解决方案1】:

    这是通过transactions 处理的。由于您没有指定我显示网络代码的技术:

    balanceRef.transaction(function(current) {
      if (current && current > 10) {
        return current - 10;
      }
      return (current || 0);
    }
    

    如果多个应用程序同时运行此代码,其中一个将被拒绝其事务并重试。

    另见:

    【讨论】:

    • 它工作得很好,我也遇到了第一个doTransation 调用的问题,它返回null,你的第二个网址帮助了我。谢谢。 (Java 顺便说一句)
    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2021-11-05
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多