【发布时间】:2019-01-20 11:17:26
【问题描述】:
我正在使用 Firebase 实时数据库来构建我的应用程序 Unity。为了建立一个“朋友”排行榜,数据库将跟踪用户的朋友和他们的分数。
数据库结构如下:
scores{
user id : score
}
Users:{
Id: {
ageRange
email
name
friendlist : {
multiple friends user ids
}
}
}
问题是为了获得分数和每个朋友的名字,应用程序必须进行大量的 api 调用。至少如果我正确理解火力基地。如果用户有 10 个朋友,则需要 21 次调用才能填满排行榜。
我想出了以下用 c# 编写的代码:
List<UserScore> leaderBoard = new List<UserScore>();
db.Child("users").Child(uid).Child("friendList").GetValueAsync().ContinueWith(task => {
if (task.IsCompleted)
{
//foreach friend
foreach(DataSnapshot h in task.Result.Children)
{
string curName ="";
int curScore = 0;
//get his name in the user table
db.Child("users").Child(h.Key).GetValueAsync().ContinueWith(t => {
if (t.IsCompleted)
{
DataSnapshot s = t.Result;
curName = s.Child("name").Value.ToString();
//get his score from the scores table
db.Child("scores").Child(h.Key).GetValueAsync().ContinueWith(q => {
if (q.IsCompleted)
{
DataSnapshot b = q.Result;
curScore = int.Parse(b.Value.ToString());
//make new userscore and add to leaderboard
leaderBoard.Add(new UserScore(curName, curScore));
Debug.Log(curName);
Debug.Log(curScore.ToString());
}
});
}
});
}
}
});
还有其他方法可以做到这一点吗?我已经阅读了多个堆栈溢出问题并观看了 firebase 教程,但我没有找到任何更简单或更有效的方法来完成工作。
【问题讨论】:
-
您是否尝试过获取朋友列表而不是逐个获取?,只需通过 id 过滤器获取用户。这将创建 1 个 api 调用而不是 N 个调用。
-
@DiegoCardozo 在第一次通话中我得到了朋友列表(他们的 ID)。之后,我仍然需要获取他们的用户名并一一评分,这就是我创建 foreach 循环的原因。有没有办法喜欢在一个电话中获取这些朋友的所有用户名,而不是循环并尝试为每个朋友这样做?
-
我的意思是你已经有了 ID 列表,是你的
friendsList属性。您可以创建一个查询来获取与这些 ID 匹配的朋友列表。
标签: c# firebase unity3d firebase-realtime-database