【问题标题】:FirebaseAuth - how can I wait for valueFirebaseAuth - 我如何等待价值
【发布时间】:2021-08-10 00:57:13
【问题描述】:

我使用 FirebaseAuth 注册新用户

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

我调用上面的函数,每次我得到false。一段时间后我得到true

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

我如何等待 uth 结果(成功/失败)并获得该值?

【问题讨论】:

    标签: android firebase kotlin firebase-authentication kotlin-coroutines


    【解决方案1】:

    FirebaseAuthenticationService 来自哪里?你需要它吗?官方入门指南只使用Firebase.auth。有了这个,您可以使用await() 挂起函数而不是使用回调方法进行身份验证。

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

    【讨论】:

      【解决方案2】:

      如果您使用协程,您可以使用suspendCoroutine,它是传统回调和协程之间的完美桥梁,因为它可以让您访问Continuation<T> 对象,例如Task<R> 对象的便利扩展功能:

          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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 1970-01-01
        • 2018-10-26
        • 1970-01-01
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多