mardi 2 avril 2019

Handling Firebase "Tasks" and implement Manager Classes (for Firebase) in Unity

I'm writing the code for a game whose server-side is totally based on Firebase. I expect to use Auth, Database, InstanceID, Messaging and Cloud Functions in the game. Being a novice C# Programmer, I encountered with C# "Tasks" first time with Firebase. I'm going to use Database for a lot of times (like Score Update, Friends Requests, Chat, Friend Did this, Friend Did that). I mostly feel comfortable with Singleton Pattern (GameManagers, EnemyManagers, SoundManagers etc..). But with Firebase, since most of its calls are asynchronous and implemented via Tasks. I think I need to workaround differently to implement Managers.

For example, I need to send a Friend Request to a specific friend. The UIManager is a script that deals with UI events etc. I'd like to call Method from this script to another Manager (say FriendsManager). But I need to first check if this friend is already friend of mine from Database or Not? So, what I would do is

class UIManager
{
   void OnFriendRequestClicked(string friendId)
   {
      bool userExists = FriendsManager.instance.UserExists(friendId);
      if(userExists)
            // Proceed with Sending Request
               FriendsManager.instance.SendRequest(friendId);
       else 
          // Show a Dialogue that User ID is invalid
          ShowError("User Id is invalid");

       // NOTE: The above code block of "condition" is executed before 
       // the UserID is validated from FriendsManager
       // I know its because of Task. But how can I alter this code 
       // to do something in the similar pattern? 
   }
}

class FriendsManager
{
   bool UserExists(string userIdToCheck)
   {
    reference.Child("users").Child(userIdToCheck).GetValueAsync().ContinueWith(
  task=>
   {
       if(task.IsCompleted)
         {
             if(task.Result == null)
                  return false;    // (expected) Return false to Method "UserExists"
             else 
                  return true;    //(expected) Return true to Method "UserExists" 

       // But this won't actually return "bool" to the method,
      // it actually returns to its own "Task"
     //NOTE: -> How to Return from here to the Method? 
   )};   
}

Aucun commentaire:

Enregistrer un commentaire