Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Problem with Task.ContinueWith using Firebase

Discussion in 'Formats & External Tools' started by Voidiotic, Dec 14, 2021.

  1. Voidiotic

    Voidiotic

    Joined:
    Jun 17, 2016
    Posts:
    8
    I have implemented a lot of Firebase functions inside of my games, and most of them uses Task.ContinueWith to keep track of the task result. However, whenever I try to call a function inside, the behavior of the game gets unpredictable. Sometimes the function completes normally, but most of the times it gets stuck without a error message, or just make the entire game crash.

    An example of what I'm doing:
    Code (CSharp):
    1. FirebaseManager.Instance.auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
    2.         {
    3.             RandomFunction();
    4.         });

    As a result, I decided to work around it by creating a coroutine to keep track of the task status and call the function from there. After I've done this, the problem disappears completely.

    The modification:
    Code (CSharp):
    1. IEnumerator TestRoutine()
    2.     {
    3.         while (task_status == "signing_in")
    4.         {
    5.             yield return null;
    6.         }
    7.         if (task_status == "success")
    8.         {
    9.             RandomFunction();
    10.         }    
    11.     }
    12.  
    13. string task_status = "signing_in";
    14. StartCoroutine(TestRoutine());
    15. FirebaseManager.Instance.auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
    16.         {        
    17.             task_status = "success";
    18.         });
    However doing this every time is a bit inconvenient. Does someone know why is this happening?
     
  2. XoetziX

    XoetziX

    Joined:
    Mar 16, 2021
    Posts:
    16
    I am not an expert, but I think it has to do with the way how threading / task work in Unity and Firebase.
    With ContinueWith a background thread is used and not the main thread of Unity. This can cause the problem that errors are hidden in the background.
    Fortunately, Firebase comes with the ContinueWithOnMainThread method, which should help you to avoid these problems.

    Additionally, this video may help you further: