c# - 使用操作回调从实时数据库中检索数据
问题描述
我正在尝试使用 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.
}
问题是我如何等待回调返回值,然后等待 .return
JsonLeaderBoardResult
解决方案
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);
});
});
}
推荐阅读
- ruby-on-rails - 如何将 NGINX 配置为仅服务器一个静态文件?
- android - 为什么 React Native Picker 在我的 Android 模拟器中不起作用?
- c# - ASP.NET 自定义 WebHook 实现
- amazon-web-services - env.yml 与 .config 之间的 AWS Elastic Beanstalk 区别
- java - Java Spring Application,经过HTTP请求方法
- typescript - 使用bind时如何对this的typescript类型说?
- android - 如何在 Android Studio 中禁用 lambda 功能?
- python - 简单的加法问题在python中不起作用
- python - Matplotlib:如何只显示一个图形而不关闭其他图形?
- javascript - 从我的桌面复制 S3 存储桶文件后未显示