Hey, I have a login fun and I want it to wait for ...
# android
n
Hey, I have a login fun and I want it to wait for .signInWithEmail.. to finish and then based on it's result, to do something and return a TaskResult. Now the problem is that the onCompleteListener doesn't happen before the last return. Is there a way to wait for its completion? I looked into .async and .await but didn't find any useful docs. If anyone can point me in the right direction it would be appreciated. (this is in my RemoteDataSource and the Repository calls the Login fun)
Copy code
fun Login(email: String, password: String): TaskResult {
         var taskResult = TaskResult.LOADING

          firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener { 
              if(it.isSuccessful){
                  taskResult = TaskResult.SUCCESS
              }
          }

         return taskResult // THIS TRIGGERS BEFORE THE ONCOMPLETELISTENER, so I always get TaskResult.Loading back
     }
I am also looking to run this in a coroutine
r
You can use Continuation with suspendCoroutine :
Copy code
suspend fun login(...): TaskResult = suspendCoroutine { cont ->
        firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener {
            if (it.isSuccessful) {
                taskResult = TaskResult.SUCCESS
                cont.resume(taskResult)
            }
        }
    }
1
a
you'll probably want to use
suspendCancellableCoroutine
so that you can resume things based on job cancellation; firebase
Task
doesn't support cancelling the actual work but you can clean up your own code at least
n
Thanks! I will look into it, didn't know about this.
a
(slight correction:
Task
itself doesn't support it but some rare firebase operations support passing a cancellation token forward and you can wire that up to the coroutines cancellation mechanism when it's available. It's not very consistent.)