我想在“DAL”類中呼叫 Firebase 函式,因為我想創建一些抽象。我無法弄清楚如何從回呼內部回傳變數,或者如何傳入回呼以從我創建的控制器類中執行。我如何使 UserExistsInFirebase 異步并從控制器類中呼叫它
public void GetUser() {
bool exists = await firebase.UserExistsInFirebase("User1");
}
public Task<bool> UserExistsInFirebase(string Username)
{
bool isExists = false;
reference.Child("Users").Child(Username).Child("Username").Child(Username).GetValueAsync().ContinueWithOnMainThread(task =>
{
if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
//checks to see if we found another user with the same username
if (snapshot.GetValue(true) != null)
{
isExists = true;
}
}
});
return isExists;
}
uj5u.com熱心網友回復:
在您當前的代碼中,問題是ContinueWithInMainThread任務完成后一段時間后呼叫回呼。與此同時,它根本不會阻止你UserExistsInFirebase,而是直接繼續并回傳false。
請注意,需要一種方法才能async在await其中使用;)
因此,ContinueWithInMainThread您寧愿完成您的任務async并await再次使用。
public async Task<bool> UserExistsInFirebase(string Username)
{
var snapShot = await reference.Child("Users").Child(Username).Child("Username").Child(Username).GetValueAsync();
return snapShot.GetValue(true) != null;
}
現在這不會在主執行緒中回傳;)
但是,您可以再次確保通過使用例如
public void GetUser()
{
firebase.UserExistsInFirebase("User1").ContinueWithOnMainThread(exists =>
{
// Do something with the bool exists after the request has finished
});
// again anything here would be immediately executed before the request is finihed
}
所以基本上你剛剛抽象了任務,但將回呼的處理保持在你開始請求的頂層。
如果您仍然希望像以前一樣進行錯誤處理,您可能還可以執行類似的操作
public async Task<bool> UserExistsInFirebase(string Username)
{
bool isExists = false;
await reference.Child("Users").Child(Username).Child("Username").Child(Username).GetValueAsync().ContinueWith(task =>
{
if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
//checks to see if we found another user with the same username
if (snapshot.GetValue(true) != null)
{
isExists = true;
}
}
});
return isExists;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/428506.html
上一篇:用于清理RGB地面實況分割掩碼的最近鄰插值,PythonNumpy
下一篇:抽象類java繼承
