Home > other >  Firebase RTDB Unity - RunTransaction Always Returns Null
Firebase RTDB Unity - RunTransaction Always Returns Null

Time:09-05

Initial call is:

    db_reference
    .Child("total_users")
    .RunTransaction(RunTransaction)
    .ContinueWithOnMainThread(task => {
        if (task.Exception != null) {
            Debug.Log("Transaction exception.");
        } else if (task.IsCompleted) {
            Debug.Log("Transaction complete.");
        }
    });

Which calls:

TransactionResult RunTransaction(MutableData mutableData) {
    List<object> data = mutableData.Value as List<object>;
    if (data != null) {
        Debug.Log("data not null: "   data);
        // I want to increment data here but mutableData always null       
    } else {
        Debug.Log("data null");
    }
    return TransactionResult.Success(mutableData);
}

Aim is to simply get a value from the mutable data and increment it, however this always returns null and never the data stored in RTDB. Transaction also completes without error other than logging null.

  • Firebase Unity SDK 9.4.0
  • Unity Version: 2021.3.9f1

In addition when I update the value when null:

TransactionResult RunTransaction(MutableData mutableData) {
    List<object> data = mutableData.Value as List<object>;
    if (data != null) {
        Debug.Log("data not null: "   data);
        // I want to increment data here but mutableData always null       
    } else {
        Debug.Log("data null");
        // settings default value as per docs below
        Dictionary<string, object> newData = new Dictionary<string, object>();
        newData["total_users"] = 1;
        mutableData.Value = newData;
    }
    return TransactionResult.Success(mutableData);
}

this does update the value in RTDB successfully BUT this seems to override the actual value stored, which is not coming through and always shows null for the mutableData received.

Any help much appreciated.

CodePudding user response:

Getting an initial null for the current value is the expected behavior.

Firebase immediately invokes your callback with its best guess at the current value of the node, which is usually null. Even when you know that this cannot ever be the value, the SDK can't know that. So your code should handle the null (for example by returning an initial value like 0), and will then be called again once the SDK has gotten the updated current value from the server.

Also see:

  • Related