https://kotlinlang.org logo
#android
Title
# android
n

Nikola Milovic

01/11/2020, 4:13 PM
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

Richard Phol

01/11/2020, 4:35 PM
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

Adam Powell

01/11/2020, 4:42 PM
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

Nikola Milovic

01/11/2020, 4:45 PM
Thanks! I will look into it, didn't know about this.
a

Adam Powell

01/11/2020, 4:47 PM
(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.)