首页 > 解决方案 > 使用操作回调从实时数据库中检索数据

问题描述

我正在尝试使用 Unity 从 Firebase 实时数据库接收 JSON 值。

我执行以下操作:

   FirebaseDatabase.DefaultInstance
          .GetReference("Leaders").OrderByChild("score").GetValueAsync().ContinueWith(task =>
                    {
                        if (task.IsFaulted)
                        {
                            Debug.LogError("error in reading LeaderBoard");
                            return;
                        }
                        else if (task.IsCompleted)
                        {
                            Debug.Log("Received values for Leaders.");
                            string JsonLeaderBaord = task.Result.GetRawJsonValue();
                            callback(JsonLeaderBaord);
                        }
        }
  });

尝试阅读回调:

private string GetStoredHighScores()
    {
      private string JsonLeaderBoardResult;
      DataBaseModel.Instance.RetriveLeaderBoard(result =>
            {
                JsonLeaderBoardResult = result; //gets the data

            });
  return JsonLeaderBoardResult; //returns Null since it doesn't wait for the result to come.
}

问题是我如何等待回调返回值,然后等待 .returnJsonLeaderBoardResult

标签: c#firebaseunity3dfirebase-realtime-database

解决方案


return JsonLeaderBoardResult;//返回 Null,因为它不等待结果的到来。

RetriveLeaderBoard函数不会立即返回。您可以使用协程等待它,也可以JsonLeaderBoardResult通过Action. 在您的情况下使用Action更有意义。

将字符串返回类型更改为 void 然后通过以下方式返回结果Action

private void GetStoredHighScores(Action<string> callback)
{
    string JsonLeaderBoardResult;
    DataBaseModel.Instance.RetriveLeaderBoard(result =>
            {
                JsonLeaderBoardResult = result; //gets the data
                if (callback != null)
                    callback(JsonLeaderBoardResult);
            });
}

用法:

GetStoredHighScores((result) =>
{
    Debug.Log(result);
});

编辑:

这很好,但是在 Action 之外的 `GetStoredHighScores' 中得到结果后仍然需要做一些事情,否则我会得到一个错误,比如:get_transform 只能从主线程调用。

您收到此错误是因为RetriveLeaderBoard从另一个线程上运行。UnityThread从这篇文章中获取然后在主线程上使用UnityThread.executeInUpdate.

您的新代码:

void Awake()
{
    UnityThread.initUnityThread();
}

private void GetStoredHighScores(Action<string> callback)
{
    string JsonLeaderBoardResult;
    DataBaseModel.Instance.RetriveLeaderBoard(result =>
            {
                JsonLeaderBoardResult = result; //gets the data

                UnityThread.executeInUpdate(() =>
                {
                    if (callback != null)
                        callback(JsonLeaderBoardResult);
                });
            });
}

推荐阅读