You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Firebase事务代码实现下载额度从5倒计时至0后停止

Firebase 下载额度事务逻辑修改方案

需求背景

原有代码用于实现点赞计数的事务逻辑,现需调整为下载额度管理:

  • 用户注册时downloads字段初始化为0
  • 用户观看激励广告后,获得5次下载额度
  • 每次消耗下载额度时数值递减,减至0后不再继续减少

原有代码:

ref.child("downloads").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        if (mutableData.getValue() != null) {
            int value = mutableData.getValue(Integer.class);
            if (increment) {
                value++;
            } else {
                value--;
            }
            mutableData.setValue(value);
        }
        return Transaction.success(mutableData);
    } 
});

修改后的代码

ref.child("downloads").runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        Integer currentValue = mutableData.getValue(Integer.class);
        // 处理未初始化的字段,默认设为0
        if (currentValue == null) {
            currentValue = 0;
        }

        if (increment) {
            // 观看广告后增加5次下载额度
            currentValue += 5;
        } else {
            // 消耗额度时确保数值不低于0
            currentValue = Math.max(currentValue - 1, 0);
        }

        mutableData.setValue(currentValue);
        return Transaction.success(mutableData);
    } 
});

关键调整说明

  • 空值处理:新增对currentValue为null的判断,默认初始化为0,避免空指针异常
  • 额度增加逻辑:当increment为true(触发观看广告事件)时,在当前额度基础上加5次(若需求为每次看广告重置为5次,可将currentValue += 5改为currentValue = 5)
  • 额度消耗限制:使用Math.max(currentValue - 1, 0)保证消耗操作后数值不会低于0,达到0后不再减少
  • 事务完整性:无论数值是否变更,都执行setValue操作,确保事务能正确提交并同步到数据库

内容的提问来源于stack exchange,提问作者Mark Harrop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:55:20