Skip to content Skip to sidebar Skip to footer

Firebaseauth - How Can I Wait For Value

I use FirebaseAuth for registration new user class FirebaseAuthenticationServiceImpl(): FirebaseAuthenticationService { override fun registerWithEmailAndPasswo

Solution 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
}

Solution 2:

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) }
    
    }
    
    privatefun<R> Continuation<R>.suspendTask(task: Task<R>) {
            task.addOnSuccessListener { this.success(it) }
                .addOnFailureListener { this.failure(it) }
        }

    privatefun<R> Continuation<R>.success(r : R) = resume(r)
    privatefun<R> Continuation<R>.failure(t : Exception) = resumeWithException(t)

Post a Comment for "Firebaseauth - How Can I Wait For Value"