0

I use FirebaseAuth for registration new user

class FirebaseAuthenticationServiceImpl(): FirebaseAuthenticationService {
        
            override fun registerWithEmailAndPassword(email: String, password: String): Boolean {

                val registration = FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
                    .addOnSuccessListener {
                        println(it.additionalUserInfo?.providerId.toString())
                    }.addOnFailureListener {
                        println(it.message.toString())
                    }
                return registration.isSuccessful
            }
}

I call function above and every time I get false. After some time I get true

    coroutineScope {
                try {
                    if (firebaseService.registerWithEmailAndPassword(email, password)) {
                        openHomeActivity.offer(Unit)
                    } else {}
                } catch (e: Exception) {}
   }

How can I wait for uth result (success/failure) and afer that get that value?

Wafi_ck
  • 1,045
  • 17
  • 41

2 Answers2

1

Where is FirebaseAuthenticationService from? Do you need it? The official getting started guide just uses Firebase.auth. With this, you can authenticate using the await() suspend function instead of using the callback approach.

// In a coroutine:
val authResult = Firebase.auth.registerWithEmailAndPassword(email, password).await()
val user: FirebaseUser = authResult.user
if (user != null) {
    openHomeActivity.offer(Unit)
} else {
    // authentication failed
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
1

If you are using coroutines you can use suspendCoroutine which is perfect bridge between traditional callbacks and coroutines as it gives you access to the Continuation<T> object, example with a convenience extension function for Task<R> objects :

    scope.launch {
    
       val registrationResult = suspendCoroutine { cont -> cont.suspendTask(FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) }
    
    }
    
    private fun <R> Continuation<R>.suspendTask(task: Task<R>) {
            task.addOnSuccessListener { this.success(it) }
                .addOnFailureListener { this.failure(it) }
        }

    private fun <R> Continuation<R>.success(r : R) = resume(r)
    private fun <R> Continuation<R>.failure(t : Exception) = resumeWithException(t)
Mark
  • 9,604
  • 5
  • 36
  • 64