1
\$\begingroup\$

I'm using Firebase Realtime Database and I'm trying to compare if a name is available to other user. The problem is the method finish before the Firebase's method finish its execution. Here is the code:

private bool IsNameAvailable (string nick) 
{
    bool available = false;
    FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task => {
        if (task.IsFaulted) {
            Debug.LogError ("A error encountered: " + task.Exception);
        } else if (task.IsCanceled) {
            Debug.LogError ("Canceled ...");
        } else if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            available = (snapshot.GetValue (true) == null);
        }
    });
    return available; //This line executed before the Firebase's method end.
}

What can i do?? Thanks in advance.

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Preventing that method from continuing until the Firebase database has returned a value would be a bad idea, because it would freeze the whole game process. So a function bool IsNameAvailable (string nick) is simply not going to work when it needs to access a remote resource. You will have to work with asynchronously called callback-methods in this case. There is really no good way around it.

That means you don't have a IsNameAvailable method which returns bool, you have one which returns void and receives a method as an additional parameter which gets called as soon as it got a result from the database.

So instead of this code:

 if (IsNameAvailable (nick) ) {
    textlabel.text = "Name is available";
 } else {
    textlabel.text = "Name is already taken";
 }

You will have to pass a callback-method to IsNameAvailable which gets executed as soon as the database is finished:

 IsNameAvailable (nick, NameCheckCallback);

 /*...*/

 private void NameCheckCallback(bool success) {
     if (success) {
        textlabel.text = "Name is available";
     } else {
        textlabel.text = "Name is already taken";
     }
 }

Your IsNameAvailable function would then look like this:

private void IsNameAvailable (string nick, Action<bool> callbackFunction) 
{
    FirebaseDatabase.DefaultInstance.GetReference ("users").OrderByChild ("name").EqualTo (nick).GetValueAsync ().ContinueWith (task => {
        if (task.IsFaulted) {
            Debug.LogError ("A error encountered: " + task.Exception);
        } else if (task.IsCanceled) {
            Debug.LogError ("Canceled ...");
        } else if (task.IsCompleted) {
            DataSnapshot snapshot = task.Result;
            callbackFunction(snapshot.GetValue(true) == null);
        }
    });
}
\$\endgroup\$
1
  • \$\begingroup\$ Thanks so much! (I forgot to thanks you before, but that answer help me a lot!) \$\endgroup\$ Jul 30, 2018 at 10:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .