简体   繁体   中英

FirebaseAuth - how can I wait for value

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?

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
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM